使用 preg_replace 时如何忽略字符串中的某些单词
How to ignore some words inside string when using preg_replace
我想做的是
$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";
$output = preg_replace("/\[h1\](.*?)\[\/h1]/", "<h1></h1>", $var);
echo $output;
这里我想先忽略[/h1]
才能让结果正确,我该如何实现呢?有没有办法只获取第一个和最后一个标签?
我不知道我应该做什么或尝试,我还不够好,无法尝试,
已编辑
输出为
<h1>This is Just a text, [h1]and this inside it</h1> This just example[/h1]
但我希望得到
<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
您可以制作自己的函数,然后使用 preg_replace 限制 1,如下所示:
<?php
$var = "<h1>This is Just a text, [h1]and this inside it</h1> This just example[/h1]";
function replace_first($from, $to, $replace){
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $replace, 1);
}
$output = replace_first('[h1]', '<h1>', $var);
$output = replace_first('[/h1]', '</h1>', $output);
// Output (HTML Source Code) will be <h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
?>
注意:这是第 3 次更新,但如果问题进一步更新可能无法正常工作。
如果您只是想将字符串 [h1]
替换为 <h1>
等
,则无需使用正则表达式即可获得所需的输出。
<?php
$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";
echo str_replace(['[h1]', '[/h1]'], ['<h1>', '</h1>'], $var);
结果:
<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
我想做的是
$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";
$output = preg_replace("/\[h1\](.*?)\[\/h1]/", "<h1></h1>", $var);
echo $output;
这里我想先忽略[/h1]
才能让结果正确,我该如何实现呢?有没有办法只获取第一个和最后一个标签?
我不知道我应该做什么或尝试,我还不够好,无法尝试,
已编辑
输出为
<h1>This is Just a text, [h1]and this inside it</h1> This just example[/h1]
但我希望得到
<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
您可以制作自己的函数,然后使用 preg_replace 限制 1,如下所示:
<?php
$var = "<h1>This is Just a text, [h1]and this inside it</h1> This just example[/h1]";
function replace_first($from, $to, $replace){
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $replace, 1);
}
$output = replace_first('[h1]', '<h1>', $var);
$output = replace_first('[/h1]', '</h1>', $output);
// Output (HTML Source Code) will be <h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
?>
注意:这是第 3 次更新,但如果问题进一步更新可能无法正常工作。
如果您只是想将字符串 [h1]
替换为 <h1>
等
<?php
$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";
echo str_replace(['[h1]', '[/h1]'], ['<h1>', '</h1>'], $var);
结果:
<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>