Php正则表达式问题

时间:2012-05-31 12:57:00

标签: php regex

我试图在下面的文字中找到包含链接的句子:

<p> Referencement PG1 est spécialiste en référencement depuis 2004. Une recherche sur <a rev="help" dir="rtl" href="http://www.referencement-site-pro.com Mot Clé</a>, aidera de nous trouver. Fascinez le regard avec le film vidéo. Vous demeurerez persistant sur les plateformes Youtube, Dailymotion ... Les images Video apparaissant dans les index de Google appâteront les surfeurs. <img style="padding:5px;float:left" src="http://thumbs.virtual-tour.tv/referencementpage1.jpg Par le appel à la Vidéo, faites-vous connaître. </p>

这意味着这句话:

Une recherche sur <a rev="help" dir="rtl" href="http://www.referencement-site-pro.com Mot Clé</a>, aidera de nous trouver.

我正在使用这个正则表达式:

([A-Z][^<]*)<a[^>]*>([^<]*)</a>([^\.!\?]*)

我找不到为什么它不起作用,它给了我一个我需要的预备句子:

Referencement PG1 est spécialiste en référencement depuis 2004. Une recherche sur <a rev="help" dir="rtl" href="http://www.referencement-site-pro.com Mot Clé</a>, aidera de nous trouver.

我错过了什么?谢谢你的帮助= D

编辑(一些代码):

preg_match_all('#([A-Z][^<\.!\?]*)<a[^>]*>([^<]*)</a>(.*[^\.!\?]*)#U', $spinnedText, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>";
foreach($matches[1] as $key=>$value){
//$spinnedText = str_replace($matches[0][$key], "<a {title=\"".$this->url."\"|} {rev=\"{index|help|bookmark|friend}\"|} {dir=\"rtl\"|}{rel=\"{friend|bookmark|help|}\"|} href=\"".$this->url."\">".trim($value)."</a>", $spinnedText);
$spinnedText = str_replace($matches[0][$key], "<a {title=\"".$this->url."\"|} {rev=\"{index|help|bookmark|friend}\"|} {dir=\"rtl\"|}{rel=\"{friend|bookmark|help|}\"|} href=\"".$this->url."\">".$matches[1][$key].$matches[2][$key].$matches[3][$key]."</a>", $spinnedText);
}

3 个答案:

答案 0 :(得分:1)

你的正则表达式仍然匹配第一句,因为它以大写字母开头。您需要从\.(?:^|[\.!?])开始,但这对您来说可能是一个问题,因为第一句话在某些情况下也可能有效。你可以用这些链接多个句子吗?重要的问题是什么定义了句子。

除了p>之后的第一句话和字符串开头的句子之外,这将适用于你所拥有的内容:

preg_match('/
   (?:           # match, but do not capture any of
   ^             # the start of the string
   |p>\s*        # or an opening or closing p tag followed by any number of spaces
   |[\.!?] )     # or sentence punctuation followed by a space
   (             # capture
   [A-Z]         # a capital letter
   .*?           # followed by any characters until
   <\/a>         # a closing anchor tag
   .*?           # followed by any characters until
   [.?!])        # closing punctuation
/x', $item, $matches);

答案 1 :(得分:0)

这称为“贪婪匹配”。这意味着正则表达式引擎通常匹配正则表达式有效的所有字符。在你的例子中,你必须限制正则表达式的START,这样它就不会贪婪地匹配不同的句子。

试试这个:

[^.!?]*<\s*a[^>]+>([^<]*)</a>[^.?!]*[.?!]

它应该匹配整个句子而已。

希望这有帮助。

答案 2 :(得分:0)

您可能希望改为使用DOM解析器:

例如:http://simplehtmldom.sourceforge.net/

他们网站的示例:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
    echo $element->src . '<br>';