Preg_replace里面有方括号[]

时间:2016-03-30 02:38:13

标签: php regex

我现在正在使用preg_replace创建一个短代码。

$content = preg_replace(
    '%\[social-lock]([^[]*)\[/social-lock]%',
    $html_str_1. '\1' . $html_str_2 . '<br/>' . $html_js,
    $content
    );
echo $content;

当我将此短代码应用于HTML内容时,我们会有类似的内容

Below content will be hidden. 

[social-lock]
Code Vip: Write something here.
[/social-lock].

浏览器的输出将显示:

Below content will be hidden. 
<div class="lock" style="display:none">
Code Vip: Write something here.
</div>

但是如果我在HTML内容中添加括号(在社交锁定之间),就像那样:

Below content will be hidden. 

[social-lock]
Code Vip: Write something here. [show the brackets here]
and it will not be hidden.
[/social-lock].

[social-lock] - [/ social-lock]中的内容应该隐藏,但事实并非如此。我认为因为括号[]里面的短代码内容。 但我找不到解决办法。

1 个答案:

答案 0 :(得分:2)

它会中断,因为您使用此([^[]*)表示除[之外的每个字符在0和无限次之间。所以它停在你的字符串中的[

要解决此问题,您可以使用(.*?),它表示在0和无限时间之间获取所有内容,但是懒惰。另外,请务必设置标记s,以便.也可以匹配新行。

相关问题