2

如何正确格式化正则表达式模式以查找包含在 ex. 像这样的东西:

Lorem ipsum dolor sit amet, *'''Consectetur adipiscing elit'''. Quisque id diam sit amet
lectus semper blandit a sit amet nibh. *'''Phasellus fermentum nisi vitae lacus'''
scelerisque dapibus.

我尝试过这样的事情:

preg_match_all("/\* \'\'\'(.+?)\'\'\'/i", $new_content, $matches);

但我得到这样的结果:

array (size=2)
  0 => 
    array (size=2)
        0 => string '* '''Consectetur adipiscing elit''''
        1 => string '* '''Phasellus fermentum nisi vitae lacus''''
  1 => 
    array (size=2)
        0 => string 'Consectetur adipiscing elit'
        1 => string 'Phasellus fermentum nisi vitae lacus'

我几乎根本不使用正则表达式,所以我不知道我在做什么!

4

1 回答 1

2

您可以使用以下模式:

$str = <<<EOF
Lorem ipsum dolor sit amet, *'''Consectetur adipiscing elit'''. Quisque id diam sit amet
lectus semper blandit a sit amet nibh. *'''Phasellus fermentum nisi vitae lacus'''
scelerisque dapibus.
EOF;

$pattern = "~\*'''(.*?)'''~s";

if(preg_match_all($pattern, $str, $matches)) {
    var_dump($matches[1]);
}

输出:

array(2) {
  [0] =>
  string(27) "Consectetur adipiscing elit"
  [1] =>
  string(36) "Phasellus fermentum nisi vitae lacus"
}

解释:

     ~      is the pattern delimiter
    \*      asterisk has to be escaped
   '''      ''' 
    ()      special matching group
   .*?      any char (except of the following ''', ? -> ungreedy)
   '''      '''
     ~      pattern delimter
     s      Option, includes newlines in .*
于 2013-05-23T13:37:06.950 回答