Recognize images from a url - Regular Expressions

0

I have a function in which recognizes the url

<?php
function findReplaceURL($text){
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($reg_exUrl, $text, $url)) {
    return preg_replace($reg_exUrl, "<a href=".$url[0]."target='_blank'>".$url[0]."</a>", $text);
    } else {
        return $text;
    }
}
?>

What I'm trying to do is to recognize, not only the url of a site but also the images that end in jpg, png and gif that come from a url. Try using this expression: "%(?<=src=\")([^\"])+(png|jpg|gif)%i" , but I do not get results.

    
asked by Stn 10.11.2018 в 02:46
source

1 answer

3

With two regular expressions I understand that the function fulfills its mission. First we detect if it is a url, if so, we ask if it is an image and if it is the correct tag.

I put the function in a command line script and the result I think is satisfactory; -)

#!/usr/bin/php -q
<?php
function findReplaceURL($text)
{
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    $reg_exImg = "/.*(png|jpg|jpeg|gif)$/";

    if(preg_match($reg_exUrl, $text, $url1)) 
    {
        if(preg_match($reg_exImg, $text, $url2))
        {
            return preg_replace($reg_exImg, "<img src='".$url2[0]."' />", $text);
        }
        else
        {
            return preg_replace($reg_exUrl, "<a href='".$url1[0]."' target='_blank'>".$url1[0]."</a>", $text);
        }
    }   
    else 
    {
        return $text;
    }
}

$urls = array("http://yahoo.es","http://prueba.com/imagen.png","ftp://prueba2.com/");

foreach($urls as $url)
{
    echo findReplaceURL($url)."\n";
}

exit:

<a href='http://yahoo.es' target='_blank'>http://yahoo.es</a>
<img src='http://prueba.com/imagen.png' />
<a href='ftp://prueba2.com/' target='_blank'>ftp://prueba2.com/</a>
    
answered by 18.11.2018 / 10:58
source