Php RegEx:获取BB[code]标记之间的代码
我正在尝试使用PHP对[code]和[PHP]标记内的字符串进行搜索。然而,我无法让它发挥作用。在其他BB标记上使用相同的正则表达式,我可以成功地获得匹配,但不能在这些标记上 到目前为止,我有:Php RegEx:获取BB[code]标记之间的代码,php,regex,match,Php,Regex,Match,我正在尝试使用PHP对[code]和[PHP]标记内的字符串进行搜索。然而,我无法让它发挥作用。在其他BB标记上使用相同的正则表达式,我可以成功地获得匹配,但不能在这些标记上 到目前为止,我有: \[(?:code|php)\](.+?)\[\/(?:code|php)\] 这应与以下内容相匹配: [code] this should be matched [/code] [php] this should be matched [/php] 我用一个匿名函数使用preg_
\[(?:code|php)\](.+?)\[\/(?:code|php)\]
这应与以下内容相匹配:
[code]
this should be matched
[/code]
[php]
this should be matched
[/php]
我用一个匿名函数使用preg_replace_callback,但该函数不会在这两个标记上被调用。如果我更改正则表达式以匹配其他标记,而不是这两个标记,则会调用它。您实际上不需要执行正则表达式。考虑:
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)
取自您正在使用的一个,它匹配除换行符以外的所有字符。将其切换到也匹配换行符的构造,例如[\s\s],或者甚至使用标志:
我还建议将[code]与[/code]匹配,并将[php]与[/php]匹配:
在这种情况下,实际代码将在匹配组2中 嗯。我刚刚发现添加/s可以解决这个问题。我原以为/m能胜任这项工作,但没有。似乎更好。我会调查的。
\[(?:code|php)\]([\s\S]+?)\[\/(?:code|php)\]
~\[(?:code|php)\](.+?)\[\/(?:code|php)\]~s
\[(code|php)\]([\s\S]+?)\[\/\1\]