2014-01-26 70 views
0

我想弄清楚一个程序员卡在preg_match上的客户端的问题。我并不擅长这些,但我的解决方案显然不起作用。这是他的要求:preg_match援助需要5

非常简单的工作。需要一个正则表达式preg_match,它匹配所有不在html标签或链接锚文本部分的字符串。

例如,如果我们有字符串:

Blah blah needle blah blah <div id='needle'>blah blah <a href='#'>needle</a> blah needle</div> 

中的preg_match应该只找针的两个实例。

这里是我的解决方案,它并没有为他们的工作需要:

<?php 
// The string 
$string = "Blah blah needle blah blah <div id='needle'>blah blah <a href='#'>needle</a> blah needle</div>"; 

// You need everything outside of the tags, so let's get rid of the tags 
// and everything in between. 
$new_string = preg_replace("/<.*>.*<\/.*>/msU","",$string); 

// Now let's match 'needle' 
preg_match_all("/needle/msU",$new_string,$matches); 

var_export($matches); 
?> 

有人告诉我,它没有工作,因为它“匹配,因此 结果为未格式化的HTML删除之前所有的HTML”。我不知道他们为什么不能做$ string2 = $ string;并将HTML字符串存储在其他地方供以后使用。我也不知道为什么这很重要,因为它只是一个preg_match而不是他们正在寻找的preg_replace。我想如果有人可以帮助一个单线preg_match_all什么的,我会非常感激。

感谢;]

回答

0

您可以使用此代码:

$pattern = <<<'LOD' 
~ 
    (?> ### all that you want to skip ### 

     <a\b [^>]*+ >    # opening "a" tag 
     (?> [^<]++ | <(?!/a>))*+ # possible content between "a" tags 
     </a>      # closing "a" tag 
    | 
     < [^>]++ >    # other tags 
    ) (*SKIP)(*FAIL) # forces the precedent subpattern to fail and 
        # forbid to retry the substring with another subpattern 
| 
    needle 
~x 
LOD; 

preg_match_all($pattern, $string, $matches); 

print_r($matches); 
+0

卡西米尔 - 完美的作品!非常感谢 ;] – Adam