str_replace正在替换所有的字符串?

时间:2018-01-02 21:07:59

标签: php

我有此功能可将图片网址转换为图片。

例如。

$titulo = "text some text http://www.unityofroanokevalley.org/wp-content/uploads/sites/4/2017/05/2017Apr30smiley-face.jpg text text";

 if(preg_match('/(https?:\/\/\S+\.(?:jpg|png|gif))/', $titulo, $matches)){
    $titulo = str_replace($titulo, $matches[0], "<img src=\"$matches[0]\">");
 }

问题是它只会输出$ titulo上的图像,它不会输出文本,只会输出<img ......出了什么问题。

2 个答案:

答案 0 :(得分:1)

str_replace()的语法很简单

str_replace($searchFor,  $replaceWith,  $originalString); 

答案 1 :(得分:0)

<?php

$titulo = "text some text http://www.unityofroanokevalley.org/wp-content/uploads/sites/4/2017/05/2017Apr30smiley-face.jpg text text";
$pattern = '/(https?:\/\/\S+\.(?:jpg|png|gif))/';
 if(preg_match($pattern, $titulo, $matches)){
    $titulo = str_ireplace( $matches[0], '<img src="'.$matches[0].'" width="60px">',$titulo);
 }
 print($titulo);
?>