我正在尝试preg_replace图像链接,但只有它以.jpg,.gif,.png结尾.
http://exampel.com/1/themes/b2/images/4/image1.jpg
Run Code Online (Sandbox Code Playgroud)
至
<img src="http://exampel.com/1/themes/b2/images/4/image1.jpg" alt="" width="" height="" />
Run Code Online (Sandbox Code Playgroud)
有人能帮我吗?
不确定它会完全回答你的问题,但你至少应该能够以此为基础......
这样的事情怎么样:
$str = <<<TEST
here is
some text and an image http://exampel.com/1/themes/b2/images/4/image1.jpg ?
and some other http://exampel.com/1/themes/b2/images/4/image1.gif and
a link that should not be replaced : http://exampel.com/test.html !
TEST;
$output = preg_replace('#(http://([^\s]*)\.(jpg|gif|png))#',
'<img src="$1" alt="" width="" height="" />', $str);
var_dump($output);
Run Code Online (Sandbox Code Playgroud)
在我的例子中,我得到以下输出:
string 'here is
some text and an image <img src="http://exampel.com/1/themes/b2/images/4/image1.jpg" alt="" width="" height="" /> ?
and some other <img src="http://exampel.com/1/themes/b2/images/4/image1.gif" alt="" width="" height="" /> and
a link that should not be replaced : http://exampel.com/test.html !' (length=301)
Run Code Online (Sandbox Code Playgroud)
两个图像链接已被替换,没有其他任何内容被触及 - 特别是,非图像链接.
我使用的正则表达匹配:
http://[^\s]*\.(jpg|gif|png)然后,将所有匹配的字符串注入<img>标记.