2017-02-03 64 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

工作很好,是的,我知道只有一個簡單的方法來做到這一點,只是不能得到它..早晨編碼.. –