我试图从HTML元素中删除标题属性。PHP preg_replace匹配HTML属性
function remove_title_attributes($input) {
return remove_html_attribute('title', $input);
}
/**
* To remove an attribute from an html tag
* @param string $attr the attribute
* @param string $str the html
*/
function remove_html_attribute($attr, $str){
return preg_replace('/\s*'.$attr.'\s*=\s*(["\']).*?\1/', '', $str);
}
但是,它不能告诉<img title="something">
和[shortcode title="something"]
之间的差异。我如何只定位HTML代码中的代码(例如<img>
或<a href=""><a>
)?
使用HTML解析器,而不是正则表达式函数。 – 2013-03-06 16:29:28
**不要使用正则表达式来解析HTML **。您无法可靠地使用正则表达式解析HTML。只要HTML从你的期望改变,你的代码就会被破坏。有关如何使用PHP模块正确解析HTML的示例,请参阅http://htmlparsing.com/php.html。 – 2013-03-06 16:30:02
[How to parse and process HTML/XML with PHP?](http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-xml-with-php) – Quentin 2013-03-06 16:43:37