很抱歉,如果已经有一些帖子出现相同的问题,但是,我尝试了所有操作,但仍然找不到我的代码似乎有问题的地方。
所以我想要用我自己的内容替换src属性的内容。例如,假设我有一个这样的HTML文档:
<div>
<p>Hello</p>
<img src="123">
<p>
<img src="abc123">
</p>
<h1>Title</h1>
<img src="w?ijais,cn,a;;sqikxiasassaswxzdvfrfr...">
</div>
我想搜索每个图像标签,剥离src值,进行一些解析,然后将其替换为另一个值。为了简单起见,这是我的带有随机逻辑的PHP代码:
//The HTML content
$content = "<div><p>Hello</p>...";
//A number I want to use to modify the src values
$id = 9;
//Starts with <img src=" and ends with "/> with any number of characters in the middle
//I escape the double quotes: \"
$pattern = "/<img src=\"(.*)\">/";
//Calling preg_replace_callback
$result = preg_replace_callback($pattern, function($matches) use($id){
changeImage($matches[0], $id);
}, $content);
echo $result;
//changeImage function
public function changeImage($image, $id){
//Stripping the src value
$img = str_replace("<img src=\"", "", $image);
$img = str_replace("\">", "", $img);
//Modifying the src value
$img = $id . "-" . $img[0] . $img[1];
//Putting back the tags
$img = "<img src=\"$img\">";
return $img;
}
结果应为:
<div>
<p>Hello</p>
<img src="9-12">
<p>
<img src="9-ab">
</p>
<h1>Title</h1>
<img src="9-w?">
</div>
这是我得到的:
<div>
<p>Hello</p>
<p>
</p>
<h1>Title</h1>
</div>
您需要返回要替换的字符串,因此从此:
$result = preg_replace_callback($pattern, function($matches) use($id){
changeImage($matches[0], $id);
}, $content);
对此:
$result = preg_replace_callback($pattern, function($matches) use($id){
return changeImage($matches[0], $id);
}, $content);
编辑:建议/<img[^>]*>/
用作正则表达式以匹配img
标签
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句