Php 正则表达式问题


Php regexp issue

我试图获取包含以下文本中链接的句子:

<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);
}

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

这将适用于您拥有的内容,除了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);

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

试试这个:

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

它应该与整个句子相匹配,仅此而已。

希望这有帮助。

你可能想看看一个 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>';