Php 使用preg_replace时如何忽略字符串中的某些单词

Php 使用preg_replace时如何忽略字符串中的某些单词,php,regex,preg-replace,Php,Regex,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>$1</h1>", $var); echo $output; 但我希望得到 <h1>This is Just a text, <h1>and this insid

我想做的是

$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";
$output = preg_replace("/\[h1\](.*?)\[\/h1]/", "<h1>$1</h1>", $var);
echo $output;
但我希望得到

<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
这只是一个文本,其中的这个只是一个示例

您可以创建自己的函数,然后使用preg\u替换为limit 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>
?>


注意:这是第三次更新,但如果进一步更新,可能无法工作

如果您只想替换
等的字符串
[h1]
,则无需使用regex即可实现所需的输出

<?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);

请提供所需的样本output@Emerald我已经编辑了我的问题。现在请不要更改您的问题要求,我需要更改太多次的答案。我看到了原始问题并将其保留,现在可以使用简单的
stru_replace
,因为OP已经更改了它;p+1尽管如此,但仍能工作。@LawrencerOne Yes OP更改了太多次。每次我更新时,问题要求都会发生变化,感谢您的理解:)@AmitGupta不,我没有太多次更新我的问题,只有一次我编辑它以添加我想要的示例,但是当我将$var=放入问题中时,您的代码将无法工作,非常感谢您尝试帮助我,非常感谢。@AmitGupta+1感谢您的努力和好意。谢谢,是的!现在用简单的stru_替换+1也可以很好地工作。这个工作就像一个符咒,你能解释一下代码吗?在str_replace中,
[]
意味着什么?这是短数组语法。其中添加了,您可以使用
str_替换(array('[h1]','[/h1]')、array('''',),$var)哦,我现在明白了,它只是一个数组,我想这是一种使用str_替换的新方法。谢谢。
<?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>