2010-02-22 33 views

回答

3

什么是这样的:

$str = <<<STR 
{{Title|Open 
Bla-bla-bla 
}} 
STR; 

$matches = array(); 
if (preg_match("/^\{\{([^\|]+)\|([^\n]+)(.*)\}\}$/s", $str, $matches)) { 
    var_dump($matches); 
} 

它会让你:

array 
    0 => string '{{Title|Open 
Bla-bla-bla 
}}' (length=28) 
    1 => string 'Title' (length=5) 
    2 => string 'Open' (length=4) 
    3 => string ' 
Bla-bla-bla 
' (length=14) 

这意味着,$matches[1]$matches[2]$matches[3]使用trim后,你会得到什么你问:-)


解释正则表达式:

  • 从字符串的开头匹配:^
  • 2个{字符,不得不进行转义,因为他们有特殊的含义
  • 东西,这不是一个|,至少一次:[^\|]+
      ()所以它的捕获之间
    • - 作为结果返回
    • |必须得逃脱的第一部分。
  • a |字符 - 必须逃脱。
  • 什么,这不是一个断行,至少一次:[^\n]+
    • ()所以之间它捕获太 - 结果
  • .*几乎“任何东西”任何数量的次 的第二部分
    • ()所以之间它捕获太 - 结果
  • 的第三部分
  • ,最后两}(逃了出来,太)
  • 和字符串的结束:$

,并注意正则表达式有s(DOTALL)改性剂;关于这个,请参见Pattern Modifiers

+0

+1用于详细解释正则表达式! – 2010-02-22 21:58:49

3
$string = "{{Title|Open 
Bla-bla-bla 
}}"; 

preg_match('/^\{\{([^|]+)\|(.*?)[\r\n]+(.*?)\s*\}\}/', $string, $matches); 
print_r($matches); 
0

在Perl:

/\{\{   # literal opening braces 
(.*?)  # some characters except new line (lazy, i. e. as less as possible) 
\|   # literal pipe 
(.*?)  # same as 2 lines above 
\n   # new line 
([\s\S]*?) # any character, including new line (lazy) 
\}\}/x;  # literal closing braces 

制作更精确的解决方案取决于你想为你的字段提取什么确切的规则。

相关问题