我正在尝试使用PHP搜索[code]
和[php]
标记中的字符串。然而,我无法做到这一点。在其他BB标签上使用相同的regex,我可以成功地获得匹配,但在这些标签上没有。
到目前为止,我有这个:
'[(?:code|php)'](.+?)'['/(?:code|php)']
这应该与以下内容相匹配:
[code]
this should be matched
[/code]
[php]
this should be matched
[/php]
我将preg_replace_callback
与一个匿名函数一起使用,但该函数不会在这两个标签上被调用。如果我更改正则表达式以匹配其他标记,但不匹配这两个标记,就会调用它。
您使用的是.
,它匹配除换行符之外的所有字符。将其切换到一个也匹配换行符的构造,例如['s'S]
,甚至使用标志/s
:
'[(?:code|php)'](['s'S]+?)'['/(?:code|php)']
~'[(?:code|php)'](.+?)'['/(?:code|php)']~s
我还建议将[code]
与[/code]
进行匹配,并与[php]
和[/php]
:进行匹配
'[(code|php)'](['s'S]+?)'['/'1']
在这种情况下,实际代码将在匹配组2中。有关详细信息,请参阅此Regex 101。
您实际上不需要执行regex。考虑:
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
取自答案