正则表达式找到并替换为preg_match_all

时间:2013-01-22 20:30:38

标签: php regex

我有点盯着这个,尝试使用preg_match_all来查找放在哈希之间的文本

##START of the text##
the text <b>starts</b> here etc
##END of the the text##
##START of the text 2##
Other version stringtext <b>starts</b> here etc
##END of the the text 2##

无论我尝试什么,有一次我得到of the text而其他时间只在哈希之间,有人可以帮助我使用正则表达式吗?

3 个答案:

答案 0 :(得分:1)

$string = '##START of the text##
the text <b>starts</b> here etc
##END of the the text##
##START of the text 2##
Other version stringtext <b>starts</b> here etc
##END of the the text 2##';

preg_match_all('/##START.+?##[\n](.+?)##END/s', $string, $matches);
// look for any characters between ##START and ##END, 's' will make it match newlines as well

print_r($matches[1]);

将输出:

Array
(
    [0] => the text <b>starts</b> here etc

    [1] => Other version stringtext <b>starts</b> here etc

)

答案 1 :(得分:1)

$str = '##START of the text##
the text <b>starts</b> here etc
##END of the the text##
##START of the text 2##
Other version stringtext <b>starts</b> here etc
##END of the the text 2##';

preg_match_all( '~##(.+)##~', $str, $matches );

print_r($ matches)yield to:

Array ( [0] => START of the text [1] => END of the the text [2] => START of the text 2 [3] => END of the the text 2 ) 

答案 2 :(得分:0)

我对正则表达式不是很好但是这里是我的解决方案,我不是用哈希匹配行开头,^是用于行开头,(?!#)是负向前瞻查找#character,m modifier用于多行。

$string = <<<EOD
##START of the text##
the text <b>starts</b> here etc
##END of the the text##
##START of the text 2##
Other version stringtext <b>starts</b> here etc
##END of the the text 2##
EOD;

preg_match_all('~^(?!#).*~m',$string,$match);
echo "<pre>";
print_r($match);

正如我所说,我是正则表达式的新手,所以专家警告我,如果我错了。