2017-03-15 77 views
0

我有这样的HTML代码:PHP正则表达式:匹配特定的词中的HTML

<html> 
<div class="the_grp"> 
<h3>heading <span id="sn-sin" class="the_decs">(keyword: <i>cat</i>)</span></h3> 
<ul> 
    <li> 
     <div> 
      <div><span class="w_pos"></span></div> 
      <div class="w_the"> 
      <a href="http://www.exampledomain.com/20111/cute-cat">cute cat</a>, 
      <a href="http://www.exampledomain.com/7456/catty">catty</a>, 
      </div> 
     </div> 
    </li> 
    <li> 
     <div> 
      <div><span class="w_pos"></span></div> 
      <div class="w_the"> 
      <a href="http://www.exampledomain.com/7589/sweet">sweet</a>, 
      <a href="http://www.exampledomain.com/10852/sweet-cat">sweet cat</a>, 
      <a href="http://www.exampledomain.com/20114/cat-vs-dog">cat vs dog</a>, 
     </div> 
    </li> 
</ul> 
</div> 

<a id="ant"></a> 
<div class="the_grp"> 
<h3>another heading <span id="sn-an" class="the_decs">(ignore this: <i>cat</i>)</span></h3> 
<ul> 
    <li> 
     <div> 
      <div><span class="w_pos"></span></div> 
      <div class="w_the"><a href="http://www.exampledomain.com/118/bad-cat">bad cat</a></div> 
     </div> 
    </li> 
</ul> 
</div> 

我要匹配html代码下面的话:

  • 可爱的猫
  • 每斤
  • sweet
  • 甜猫
  • 猫vs狗

我使用这个模式,捕捉[2]获得的那些话:

#<a href="http\:(.*?)">(.*?)<\/a>#i 

我的PHP代码是这样的:

preg_match_all('#<a href="http\:(.*?)">(.*?)<\/a>#i', $data, $matches); 
echo '<pre>'; 
print_r($matches[2]); 
echo '</pre>'; 

这种模式匹配 “坏猫”太。如何只捕捉下面这些词:可爱的猫,每斤,甜,猫,猫vs狗?

在此先感谢。

+1

我将把[此帖](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except- xhtml-self-contained-tags) – ChrisG

+0

不要使用正则表达式来解析HTML。 – Vallentin

+0

您使用的模式将匹配'a'中的所有内容。你试图做的事情就是拼凑,为此寻找一个PHP库。 – MikeVelazco

回答

0

最好只使用HTML解析器。以下是你如何使用http://simplehtmldom.sourceforge.net/来做到这一点。

file_get_html将是最好,它会调用基本的file_get_contents和str_get_html

str_get_html是你如何解析字符串为一个简单的HTML DOM对象。

<?php 

require('simple_html_dom.php'); 

$html = str_get_html(/*your html here*/); 

foreach($html->find('a') as $element) 
     echo $element->plaintext . '<br>'; 

?> 

如果你不想让坏猫匹配,只需循环遍历结果并删除/忽略它。

如果你想删除bad cat

foreach($html->find('a') as $element) 
    if ($element->plaintext != "bad cat") 
     echo $element->plaintext . '<br>';