使用RegEx删除href属性的内容

时间:2011-10-01 18:12:56

标签: php regex

例如,我有这个HTML代码段:

<a href="/sites/all/themes/code.php">some text</a>

问题是 - 如何使用/sites/all/themes/code.phphref剪切文字preg_replace();我可以使用哪种模式?

3 个答案:

答案 0 :(得分:3)

我强烈建议不要使用正则表达式来解析任何SGML派生词。

对于HTML,使用一些DOM解析器。对于PHP,具体为DOMDocument

答案 1 :(得分:0)

图案:

(<a .*?href=")([^"]*)

替换:$ 1

答案 2 :(得分:0)

你不必做“替换”

(?<=<a href=")[^"]*(?=">) 

直接为您提供所需内容。

用grep测试:

kent$  echo '<a href="/sites/all/themes/code.php">some text</a>'|grep -oP '(?<=<a href=")[^"]*(?=">)'                                    
/sites/all/themes/code.php