正则表达式语法问题 - 试图理解

Asa*_*off 1 php regex

我是一名自学成才的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).

Pet*_*hof 6

首先:从来没有使用正则表达式的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)

  • @Hugoagogo对我来说,他有一个他需要解决的实际问题.他需要正则表达式帮助的事实是基于正则表达式是解决他的问题的最佳方法的假设.虽然这个特殊问题可以用正则表达式解决,但是使用DOMDocument会更好,并且将来会证明. (2认同)