gpt4 book ai didi

php - 找到 [abc] 而不是 [;;abc] 的正则表达式

转载 作者:行者123 更新时间:2023-12-04 03:37:31 29 4
gpt4 key购买 nike

太晚了,我还不太明白。

我的文字看起来像这样:

 This is a [;;Text] and I want to match [center]everything without ;;[/center]

我用它来转换为 HTML:

 return preg_replace('/\[(.+)\]/U', '<$1>', $text);

我认为模式 /\[[^;{2}](.+)\]/U 应该可以解决问题,但它不起作用。

最佳答案

例如,您可以匹配 [ 和一个可选的 / 后跟单词字符直到结束 ]

请注意,在这种情况下,您不需要 /U 标志来使量词变得惰性。

\[/?\w+]

$text = ' This is a [;;Text] and I want to match [center]everything without ;;[/center]';
$result = preg_replace('/\[(\/?\w+)]/', "<$1>", $text);
echo $result;

输出

This is a [;;Text] and I want to match <center>everything without ;;</center>

Regex demo


对于更具体的匹配,您可以在 [ 之后排除匹配的 ;; 并匹配除 [] 之外的所有字符 使用否定的字符类。

\[(?!;;)([^][]*)]

Regex demo

关于php - 找到 [abc] 而不是 [;;abc] 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66621349/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com