Search code examples
phppreg-matchstrpos

PHP remove URL from string if URL contains specific letters


I have a string and would like to remove any URLs that are image URLs, ex. contain a .jpg ending.

I am able to extract and separate the image URL from a string with preg_match_all and strpos, but now I need to "remove" the displayed image URL from the string itself (so that I can treat the image separately from the string)

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;   
   }
}

Input

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

Desired Output:

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

Solution

  • String replacement on match could do this one for you

    <?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;   
       }
    }
    

    Hope this helps.


    EDIT:

    Remove unenecessary variable use for you, no need for the storage of the strpos result in the example above.

    EDIT 2: Fixed syntax error with $link string concatenation.