如果URL包含特定字母,PHP将从字符串中删除URL

时间:2017-10-04 19:09:48

标签: php preg-match strpos

我有一个字符串,并希望删除任何图片网址,例如。包含.jpg结尾。

我能够使用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"/>';

2 个答案:

答案 0 :(得分: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;   
   }
}

希望这有帮助。

编辑:

为您删除不必要的变量使用,无需在上面的示例中存储strpos结果。

编辑2:修复了$ link string concatenation的语法错误。

答案 1 :(得分:0)

您可以使用til方法检查字符串,    $ list =你要检查的内容    $ endOfString =你要找的东西

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

    return (substr($list, -$length) === $endOfString);
}
相关问题