2017-02-03 65 views
0

我正在研究一些代码,并且我已经做了足够的工作来完成某些任务。我想在文本主体中替换图片网址和网页链接。Php preg_match和preg_replace带有url和图像标签的文本

EG“这是我的文字与http://www.google.com和某些图像http://www.somewebimage.png

替换为“这是我的文字与<a href="http://www.google.com">http://www.google.com</a>和某些图像<img src="http://www.somewebimage.png">

我砍得我更换网址或者IMG的链接,但并不both..one是在写入的,因为为了

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/'; 
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png"; 

if(preg_match($reg_exImg, $post, $img)) { 
    $img_post = preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post); 
} else { 
    $img_post = $post; 
} 
if(preg_match($reg_exUrl, $post, $url)) { 
    $img_post = preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post); 
} else { 
    $img_post = $post; 
} 

的如果我阻止了$ reg_exUrl代码块,我得到的图像链接,如果它运行的我得到的URL链接。

+0

我想要做的是一个简单的饲料,其中的URL链接被和IMG的URL被嵌入.. –

+0

第一件事,测试用图案'preg_match'在与'preg_replace'一起使用之前是没有用的。 –

+0

您应该为这两种情况使用单一模式,然后使用'preg_replace_callback'选择替换模板。这样一切都是一次完成的,没有任何东西被覆盖。在回调函数中,您可以使用'parse_url'和'explode'来轻松提取文件扩展名。 –

回答

0

你可以一次完成它,你的两个模式非常相似,并且很容易构建一个处理这两种情况的模式。使用preg_replace_callback,你可以选择在回调函数替换字符串:

$post = "This is my text with http://www.google.com and some image http://www.domain.com/somewebimage.png"; 

# the pattern is very basic and can be improved to handle more complicated URLs 
$pattern = '~\b(?:ht|f)tps?://[a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?~i'; 
$imgExt = ['.png', '.gif', '.jpg', '.jpeg']; 
$callback = function ($m) use ($imgExt) { 
    if (false === $extension = parse_url($m[0], PHP_URL_PATH)) 
     return $m[0]; 

    $extension = strtolower(strrchr($extension, '.')); 

    if (in_array($extension, $imgExt)) 
     return '<img src="' . $m[0] . '" width="300" style="float: right;">'; 
    # better to do that via a css rule --^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
    return '<a href="' . $m[0] . '" target="_blank">' . $m[0] . '</a>'; 
}; 

$result = preg_replace_callback($pattern, $callback, $post); 
+0

工作很好,是的,我知道只有一个简单的方法来做到这一点,只是不能得到它..早晨编码.. –