你不想要正则表达式。虽然您可以使用简单的正则表达式(例如发布的一个 webbandit)来完成您尝试为最基本的案例所做的事情,但它将打破更复杂的示例(例如我评论中的示例)。
这可以通过更好的正则表达式和前瞻来解决,但这不是你想要的。你正在做字符串匹配,你应该使用有限的机器来完成它。PHP 的字符串算法可以给你一些快速而肮脏的东西,它会更好地工作,例如
<?php
$text = "[reply] something [reply] bla bla bla [reply] something else [reply]";
$matches = array();
$lastMatch = 0;
$matchCount = 0;
$search = "[reply]";
while(true) {
$thisMatch = strpos($text, $search, $lastMatch+1);
if($thisMatch === FALSE)
break;
if(++$matchCount % 2 == 0)
{
$lastMatch = $thisMatch;
continue;
}
//print substr($text, $lastMatch + strlen($search), $thisMatch - $lastMatch - strlen($search)) . "\n";
array_push($matches, substr($text, $lastMatch + strlen($search), $thisMatch - $lastMatch - strlen($search)));
$lastMatch = $thisMatch;
}
print_r($matches);
?>
会给你一系列的回复$matches
。
输出:
[mqudsi@iqudsi:~/Desktop]$ php reply.php
Array
(
[0] => something
[1] => something else
)
对于您修改后的问题[reply]
and [/reply]
,解决方案在这里:
$text = "[reply] something [/reply] bla bla bla [reply] something else [/reply]";
$matches = array();
$end = -1;
while(true) {
$start = strpos($text, "[reply]", $end+1);
$end = strpos($text, "[/reply]", $start+1);
if($start === FALSE || $end === FALSE)
break;
array_push($matches, substr($text, $start + strlen("[reply]"), $end - $start - strlen("[reply]")));
$lastMatch = $thisMatch;
}