我试图从文本中获取所有出现的代码段和3个参数.
我使用正则表达式和preg_match_all PHP函数进行此操作.
如果我在文本中只出现了一个摘录,则效果很好.
如果有两个或多个,我会得到一个奇怪的结果.
我对正则表达式不是很熟练,因此我很难理解我所缺少的东西.
public function getgallerySnippetoccurrences($text) {
$ptn = '/{# +gallery +(src|width|height)=\[(.*)\] +(src|width|height)=\[(.*)\] +(src|width|height)=\[(.*)\] +#}/';
if(preg_match_all($ptn,$text,$matches)){
$turnedMatches = $this->turn_array($matches);
return $turnedMatches;
}
else {
return null;
}
}
文本1(在这种情况下按方面使用)
Lorem ipsum {# gallery src=[holiday_images/london] width=[400] height=[300] #} sid amet.
返回值:
array(1) {
[0] =>
array(7) {
[0] =>
string(66) "{# gallery src=[holiday_images/london] width=[400] height=[300] #}"
[1] =>
string(3) "src"
[2] =>
string(21) "holiday_images/london"
[3] =>
string(5) "width"
[4] =>
string(3) "400"
[5] =>
string(6) "height"
[6] =>
string(3) "300"
}
}
文字2(未预期的行为)
Lorem ipsum {# gallery src=[holiday_images/london] width=[400] height=[300] #} sid amet {# gallery src=[holiday_images/paris] width=[400] height=[300] #}
退货
array(1) {
[0] =>
array(7) {
[0] =>
string(141) "{# gallery src=[holiday_images/london] width=[400] height=[300] #} sid amet {# gallery src=[holiday_images/paris] width=[400] height=[300] #}"
[1] =>
string(3) "src"
[2] =>
string(96) "holiday_images/london] width=[400] height=[300] #} sid amet {# gallery src=[holiday_images/paris"
[3] =>
string(5) "width"
[4] =>
string(3) "400"
[5] =>
string(6) "height"
[6] =>
string(3) "300"
}
}
我究竟做错了什么?
解决方法:
正如我在下面的评论中所指出的那样,使量词变为非贪婪将使其起作用.但是,这仍然会使您的正则表达式重复且效率低下.
您可以针对以下两点考虑使用这种方法:
$re = '/{\#
\h+gallery
\h+(src|width|height)=\[([^]]*)]
\h+((?1))=\[([^]]*)]
\h+((?1))=\[([^]]*)]
\h*\#}/x';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
>请注意此正则表达式如何定义子模式并使用(?1)在整个正则表达式中重用它以避免重复
>还请注意使用效率更高的否定类[^]] *而不是效率低的.*?捕捉价值.