问题描述
我有这样的字符串:
我试图用正则表达式替换PHP中的源属性(可能是图像或任何标签) p>
$ string2 =< html>< body>< img src ='images / test.jpg'/>< ; img src ='http://test.com/images/test3.jpg'/><video controls =controlssrc ='.. / videos / movie.ogg'>< / video><< ; /体>< / HTML>中;
我想将它变成:
$ string2 =< html>< body>< img src ='test.jpg'/>< img src ='test3.jpg'/> < video controls =controlssrc ='movie.ogg'>< / video>< / body>< / html>;
继承人我试过的:
<$ p $ convert_url('$ 1')p> $ string2 = preg_replace(/ src = [']([/])(。*)?['''/',''src ='。 '''',$ string2);
echo htmlentities($ string2);
基本上它没有改变任何东西,并给我一个关于未转义字符串的警告。 b
$ b
不是 $ 1
发送字符串的内容吗?这里有什么问题?
convert_url的功能来自于我前面发布的示例:
<$ p $如果(preg_match('#^ https?://#',$ url)){
$ url ='code',则函数convert_url($ url)
{ parse_url($ url,PHP_URL_PATH);
}
返回基本名称($ url);
}
它应该去掉url路径并返回文件名。
e
修饰符。 b $ string =< html>< body>< img src ='images / test.jpg'/>< img src =' < / video>< /体>< / HTML>中;
$ string2 = preg_replace(〜src = [']([^'] +)[']〜e,'src = \'。convert_url($ 1)。 \'',$ string);
请注意,使用 e
修饰符时,替换脚本片段必须是字符串,以防止在调用preg_replace之前解析它。
I'm trying to use regex to replace source attribute (could be image or any tag) in PHP.
I've a string like this:
$string2 = "<html><body><img src = 'images/test.jpg' /><img src = 'http://test.com/images/test3.jpg'/><video controls="controls" src='../videos/movie.ogg'></video></body></html>";
And I would like to turn it into:
$string2 = "<html><body><img src = 'test.jpg' /><img src = 'test3.jpg'/><video controls="controls" src='movie.ogg'></video></body></html>";
Heres what I tried :
$string2 = preg_replace("/src=["']([/])(.*)?["'] /", "'src=' . convert_url('$1') . ')'" , $string2);
echo htmlentities ($string2);
Basically it didn't change anything and gave me a warning about unescaped string.
Doesn't $1
send the content of the string ? What is wrong here ?
And the function of convert_url is from an example I posted here before :
function convert_url($url)
{
if (preg_match('#^https?://#', $url)) {
$url = parse_url($url, PHP_URL_PATH);
}
return basename($url);
}
It's supposed to strip out url paths and just return the filename.
You have to use the e
modifier.
$string = "<html><body><img src='images/test.jpg' /><img src='http://test.com/images/test3.jpg'/><video controls=\"controls\" src='../videos/movie.ogg'></video></body></html>";
$string2 = preg_replace("~src=[']([^']+)[']~e", '"src=\'" . convert_url("$1") . "\'"', $string);
Note that when using the e
modifier, the replacement script fragment needs to be a string to prevent it from being interpreted before the call to preg_replace.
这篇关于正则表达式来替换PHP中的html src属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!