Home > Backend Development > PHP Tutorial > 求替换全局img图片的正则表达式

求替换全局img图片的正则表达式

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-23 13:54:49
Original
1057 people have browsed it

如题
现在有一字符串是

$content = '

求替换全局img图片的正则表达式求替换全局img图片的正则表达式test

';

想要将这字符里面的 images/tmp 都替换成 images/pub

本人已经写了一个函数
	public static function replace_img_publish_path($content){		$pattern='/(<[img|IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/';		$replacement="\${1}images/pub/\${3}";		print  preg_replace($pattern, $replacement, $content);		exit;	}
Copy after login


输出结果为

求替换全局img图片的正则表达式求替换全局img图片的正则表达式test



只替换了最后一个img标签

如何才能全部都替换?


回复讨论(解决方案)

$content = '<p><img  src="http://localhost:8080/story/images/tmp/1403530150545.jpg"   style="max-width:90%" alt="求替换全局img图片的正则表达式" ><img  src="http://localhost:8080/story/images/tmp/1403530147265.jpg"   style="max-width:90%" alt="求替换全局img图片的正则表达式" >test</p>';$content = preg_replace('#(?<=src="http://localhost:8080/story/images/)tmp/#', 'pub/', $content);echo $content;
Copy after login

求替换全局img图片的正则表达式求替换全局img图片的正则表达式test


你没有防止贪婪匹配。

$pattern='/(<[img|IMG].+?src=\"?.+?)(images\/tmp\/)(.+?\.(jpg|gif|bmp|bnp|png)\"?.+?>)/';

你写的方法加一个参数U就可以了。
加上U,将懒惰匹配 变成 贪婪匹配。

$pattern='/(<[img|IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/ U';

测试例子:

$content = '<p><img  src="http://localhost:8080/story/images/tmp/1403530150545.jpg"   style="max-width:90%" alt="求替换全局img图片的正则表达式" ><img  src="http://localhost:8080/story/images/tmp/1403530147265.jpg"   style="max-width:90%" alt="求替换全局img图片的正则表达式" >test</p>';replace_img_publish_path($content);function replace_img_publish_path($content){    $pattern='/(<[img|IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/U';    $replacement="\${1}images/pub/\${3}";    print  preg_replace($pattern, $replacement, $content);    exit;}
Copy after login


替换后:

求替换全局img图片的正则表达式求替换全局img图片的正则表达式test

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template