使用preg_match_all和遍历更多的组织和灵活性的比赛:
$str = '[fbes_keep]hello[/fbes_keep][fbes_remove]goodbye[/fbes_remove]';
preg_match_all('@([[][^]]*[]])([^[]*)([[]/[^]]*[]])@Ui', $str, $matches);
/*
// die('<pre>'.print_r($matches,true));
Array
(
[0] => Array
(
[0] => [fbes_keep]hello[/fbes_keep]
[1] => [fbes_remove]goodbye[/fbes_remove]
)
[1] => Array
(
[0] => [fbes_keep]
[1] => [fbes_remove]
)
[2] => Array
(
[0] => hello
[1] => goodbye
)
[3] => Array
(
[0] => [/fbes_keep]
[1] => [/fbes_remove]
)
)
*/
更新1
// how many matches you have is here
$count_of_matches = count($matches[0]);
// to answer your comment question...get the 3 parts for match group 0
$match_group = 0; // you also have a match_group 1
// loop over them if you like // foreach ($matches[0] as $match_group=>$full_match) {
// for now, loop over the match group 0's 3 outputs
for ($i=1; $i<4; $i++) {
echo $matches[$i][$match_group].', ';
}
// [fbes_keep], hello, [/fbes_keep],
// or access them directly
echo "{$matches[1][0]}, {$matches[2][0]}, {$matches[3][0]}";
更新2
// here is the full, double loop grabbing all of them
foreach ($matches[0] as $match_group=>$full_match) {
for ($i=1; $i<4; $i++) {
echo $matches[$i][$match_group].', ';
}
echo '<br>';
}
/* yielding
[fbes_keep], hello, [/fbes_keep],
[fbes_remove], goodbye, [/fbes_remove],
*/
的'|'s为不在,原来,他们只是在演示目的的例子。对不起,如果我困惑你。 –
为清晰起见进行了编辑。 –
尝试'preg_match(''[fbes_keep](。*?)[/ fbes_keep]'si“,$ result,$ original);' – Maik