【问题标题】:Not able to get image src using regex无法使用正则表达式获取图像 src
【发布时间】:2018-11-09 07:19:10
【问题描述】:

我正在使用下面的正则表达式在图像标签前面附加一个元素,但它不起作用。我从Add link around img tags with regexp获取此代码

preg_replace('#(<img[^>]+ src="([^"]*)" alt="[^"]*" />)#', '<a href="$2" ...>$1</a>', $str)

但是,如果我在没有 src 的情况下使用下面的代码,它可以工作。

 preg_replace('#(<img[^>]+ alt="[^"]*" />)#', '<a href="" ...>$1</a>', $str)

我无法从图像标签中获取 src 的任何原因。

我的图片标签是&lt;img src="" alt=""&gt;

【问题讨论】:

  • 试图使用正则表达式来处理 HTML 肯定是难以辨认的,并且如图所示在其他方面是严格的。尝试使用 DOMDocument 来处理它,你应该会得到更好的结果。 (尝试#(&lt;img[^&gt;]+src="([^"]*)" alt="[^"]*"&gt;)# 为您的模式,但这仍然是脆弱的)
  • @NigelRen 我试过你的模式。它仍然无法正常工作。
  • 这就是为什么我说 - 不要使用它!,正确使用 - 如果有人编码他们的锚标签 &lt;img alt="" src="" /&gt; 会发生什么?
  • 只需转义最后一个正斜杠/,以具有src 的模式。 And it will work
  • @rv7 我已经解决了这个问题,使用这个模式#(&lt;img.*?src="(.*?)"[^\&gt;]+&gt;)#。谢谢。

标签: php regex preg-replace


【解决方案1】:

更好的方法是使用 PHP 的 DOMDocument 类,因为它与人们编写 HTML 的方式无关(例如,将 alt 属性放在 src 属性之前)。这样的事情适合你的情况:

$html = '<div id="x"><img src="/images/xyz" alt="xyz" /><p>hello world!</p></div>';
$doc = new DomDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DomXPath($doc);
$images = $xpath->query('//img');
foreach ($images as $img) {
    // create a new anchor element
    $a = $doc->createElement('a');
    // copy the img src attribute to the a href attribute
    $a->setAttribute('href', $img->attributes->getNamedItem('src')->nodeValue);
    // add the a to the images parent
    $img->parentNode->replaceChild($a, $img);
    // make the image a child of the <a> element
    $a->appendChild($img);
}
echo $doc->saveHTML();

输出:

<div id="x"><a href="/images/xyz"><img src="/images/xyz" alt="xyz"></a><p>hello world!</p></div>

Demo on 3v4l.org

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多