2017-10-04 185 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); 
}