我想替换字符串中的 img 标签。替换 img 标签并添加例如 a[href] 标签与 dom 解析器配合使用效果很好,但这对我没有帮助,因为我必须更改现有 html 字符串中的标签。我知道用正则表达式更改 html 不是一个好主意,但我无法弄清楚如何在 html 字符串中更改整个 img 标签。除此之外,我需要将标签包装在 a[href] 中,其中 [href] 是通过 img 标签的属性提供的。
<img class="myclasses" width="100" src="mysource" data-image-src="another_src">
在"转换"之后,找到的任何 img 标记都应如下所示:
<a href="another_src"><img [...] src="http://myexample.me[mysource]"></a>
如果字符串中有一个图像但无法处理两个图像,我让它工作。
我希望有人能帮助我:)
您可能可以使用preg_replace_callback
来实现所需的内容,然后在回调函数中循环访问图像的属性。
例如,给定此测试字符串:
$content= <<<HTML
<img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title" data-image-src="another_src" />
<p>Some other tags. These shouldn''t be changed<br />Etc.</p>
<img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title" data-image-src="somewhere_else" />
HTML;
然后我们可以匹配图像并调用我们的替换函数:
$content= preg_replace_callback('/<img ((?:[-a-z]+="[^"]*"'s*)+)'/>/i', 'replaceImage', $content);
对于我的示例,我只是删除 data-image-src
属性并使用它来创建链接,其他所有内容都保持原样:
function replaceImage($matches) {
// matches[0] will contain all the image attributes, need to split
// those out so we can loop through them
$submatches= array();
$donelink= false;
$count= preg_match_all('/'s*([-a-z]+)="([^"]*)"/i', $matches[1], $submatches, PREG_SET_ORDER);
$result= '<img ';
for($ndx=0;$ndx<sizeof($submatches);$ndx++) {
if ($submatches[$ndx][1]=='data-image-src') {
// Found the link attribute, prepend the link to the result
$result= "<a href='"{$submatches[$ndx][2]}'">$result";
$donelink= true; // We've added a link, remember to add the closing </a>
}
// You can handle anything else you want to change on an attribute-by-attribute basis here
else {
// Something else, just pass it through
$result.= $submatches[$ndx][0];
}
}
return "$result/>".($donelink?'</a>':'');
}
在示例内容上运行它会得到:
<a href="another_src"><img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title"/></a>
<p>Some other tags. These shouldn''t be changed<br />Etc.</p>
<a href="somewhere_else"><img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title"/></a>
希望对您有所帮助!