我的 preg_replace 模式正则表达式代码在这里..
/<img(.*?)src="(.*?)"/
这是我的替换代码..
<img$1src="'.$path.'$2"
所以我想否定/排除一个条件..如果 img 标签有一个rel="customimg",不要 preg_replace 所以跳过它..
示例:跳过此行
<img rel="customimg" src="http..">
什么可能会添加到这个正则表达式模式?
我搜索了另一个帖子,但我不能完全..
我的 preg_replace 模式正则表达式代码在这里..
/<img(.*?)src="(.*?)"/
这是我的替换代码..
<img$1src="'.$path.'$2"
所以我想否定/排除一个条件..如果 img 标签有一个rel="customimg",不要 preg_replace 所以跳过它..
示例:跳过此行
<img rel="customimg" src="http..">
什么可能会添加到这个正则表达式模式?
我搜索了另一个帖子,但我不能完全..
添加负前瞻:
/<img(?![^>]*\srel="customimg")(.*?)src="(.*?)"/
因为src参数可能使用单引号或双引号,我建议你使用
preg_replace(
"/(<img\b(?!.*\brel=[\"']customimg[\"']).*?\bsrc=)([\"']).*?\2/i",
"$1$2" . $path . "$2",
$string);
要添加 url 前缀而不是完整的 url 替换,请使用
preg_replace(
"/(<img\b(?!.*\brel=[\"']customimg[\"']).*?\bsrc=)([\"'])(.*?)\2/i",
"$1$2" . $path . "$3$2",
$string);
因为我只看到正则表达式“解决方案”进来。这是使用 DOMDocument 的答案:
<?php
$path = 'the/path';
$doc = new DOMDocument();
@$doc->loadHTML('<img rel="customimg" src="/image.jpgm"><img src="/image.jpg">');
$xpath = new DOMXPath($doc);
$imageNodes = $xpath->query('//img[not(@rel="customimg")]');
foreach ($imageNodes as $node) {
$node->setAttribute('src', $path . $node->getAttribute('src'));
}
看起来这样做会更容易/更有表现力
if(strpos($haystackString, '"customimg"') === false) // The === is important
{
// your preg_replace here
}
编辑:感谢您指出缺少参数的家伙