>  기사  >  백엔드 개발  >  求轮换全局img图片的正则表达式

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

WBOY
WBOY원래의
2016-06-13 12:00:43839검색

求替换全局img图片的正则表达式
如题
现在有一字符串是

$content = '

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

';

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

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


输出结果为

求轮换全局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>';<br /><br />$content = preg_replace('#(?<=src="http://localhost:8080/story/images/)tmp/#', 'pub/', $content);<br />echo $content;

求轮换全局img图片的正则表达式pub/1403530150545.jpg" style="width: 268px;">求轮换全局img图片的正则表达式pub/1403530147265.jpg" style="width: 268px;">test



------解决方案--------------------
你没有防止贪婪匹配。

 $pattern='/(------解决方案--------------------
IMG].+?src=\"?.+?)(images\/tmp\/)(.+?\.(jpg
------解决方案--------------------
gif
------解决方案--------------------
bmp
------解决方案--------------------
bnp
------解决方案--------------------
png)\"?.+?>)/';
------解决方案--------------------
你写的方法加一个参数U就可以了。
加上U,将懒惰匹配 变成 贪婪匹配。

$pattern='/(------解决方案--------------------
IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg
------解决方案--------------------
gif
------解决方案--------------------
bmp
------解决方案--------------------
bnp
------解决方案--------------------
png)\"?.+>)/U';

测试例子:
<br />$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>';<br /><br />replace_img_publish_path($content);<br /><br />function replace_img_publish_path($content){<br />    $pattern='/(<[img<br><font color='#FF8000'>------解决方案--------------------</font><br>IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg<br><font color='#FF8000'>------解决方案--------------------</font><br>gif<br><font color='#FF8000'>------解决方案--------------------</font><br>bmp<br><font color='#FF8000'>------解决方案--------------------</font><br>bnp<br><font color='#FF8000'>------解决方案--------------------</font><br>png)\"?.+>)/U';<br />    $replacement="\${1}images/pub/\${3}";<br />    print  preg_replace($pattern, $replacement, $content);<br />    exit;<br />}<br />


替换后:

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.