2017-10-04 181 views
1

我有一個字符串,並希望刪除任何圖像URL的URL,例如。包含一個.jpg結尾。PHP從字符串中刪除URL如果URL包含特定字母

我能夠通過preg_match_all和strpos從字符串中提取和分離圖像URL,但現在我需要從字符串本身「刪除」顯示的圖像URL(以便我可以將圖像與字符串分開處理)

preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $string, $match); 

foreach ($match[0] as $link){ 
    $strpos = strpos($link, '.jpg'); 
    if ($strpos !== false){ 
     echo $link; 
     break; 
    } 
} 

輸入

$string = 'This is a string with a URL http://google.com and an image URL http://website.com/image.jpg'; 

所需的輸出:

$string 'This is the string with a URL http://google.com and an image URL'; 
$image = '<img src="http://website.com/image.jpg"/>'; 
+0

Str_replace url'' –

回答

2

字符串替換匹配時可以爲你做

<?php 

preg_match_all('#\bhttps?://[^,\s()<>]+(?:\(\w+\)|([^,[:punct:]\s]|/))#', $string, $match); 

foreach ($match[0] as $link){ 
    if (strpos($link, '.jpg') !== false){ 
     //Format the image url to an image element 
     $image = '<img src="'.$link.'" />'; 

     //To substitute the image into the string 
     echo str_replace($link, $image, $string); 
     //To remove the link from original text: 
     echo str_replace($link, '', $string); 

     break; 
    } 
} 
這一個

希望這有助於。


編輯:

刪除unenecessary變量使用了你,沒有必要對strpos的存儲導致上面的例子。

編輯2:修正了$ link字符串連接的語法錯誤。

+0

真棒!奇蹟般有效 !非常感謝 ! – rainerbrunotte

0

你可以使用直到方法來檢查字符串, $名單=要檢查什麼 $ endOfString =你找

function endsWith($list, $endOfString) 
{ 
    $length = strlen($endOfString); 
    if ($length == 0) { 
     return true; 
    } 

    return (substr($list, -$length) === $endOfString); 
}