我是一名自学成才的PHP程序员,我现在才开始掌握正则表达式的东西.当它正确完成时,我非常清楚它的功能,但这也是我需要深入研究的.所以也许有人可以帮助我,并节省我这么多小时的实验.
我有这个字符串:
here is the <a href="http://www.google.com" class="ttt" title="here"><img src="http://www.somewhere.com/1.png" alt="some' /></a> and there is <a href="#not">not</a> a chance...
Run Code Online (Sandbox Code Playgroud)
现在,我需要使用preg_match此字符串并搜索a href其中包含图像的标记,并将其替换为具有较小差异的相同标记:在标记内的title属性之后,我将要添加rel="here"属性.当然,它应该忽略里面a href没有img标签的链接('s).
首先:从来没有使用正则表达式的HTML!
使用XML解析器要好得多:创建DOMDocument,加载HTML,然后使用XPath获取所需的节点.
像这样的东西:
$str = 'here is the <a href="http://www.google.com" class="ttt" title="here"><img src="http://www.somewhere.com/1.png" alt="some" /></a> and there is <a href="#not">not</a> a chance...';
$doc = new DOMDocument();
$doc->loadHTML($str);
$xpath = new DOMXPath($doc);
$results = $xpath->query('//a/img');
foreach ($results as $result) {
// edit result node
}
$doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)