1

Hey I am trying to do 2 preg_replace: 1.make all urls to html links 2.make all images url to html img tag

But these regexs cancel the other one

<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = "!http://[a-z0-9\-\.\/]+\.(?:jpe?g|png|gif)!Ui";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.comhttp://www.ynet.co.il http://dogsm.files.wordpress.com/2011/12/d7a1d7a7d795d791d799-d793d795.jpg";

// Check if there is a url in the text
    $text = preg_replace($reg_exImg, '<img src=$0 >', $text);
    $text = preg_replace($reg_exUrl, '<a href="$0" rel="nofollow">$0</a>', $text);
    echo $text;
?>

How can I make that the preg_replace that make url to links dont do this to the tag?

Thanks.

Haim

1 Answer 1

1

This might be better as a callback.

Use just the $reg_exUrl, and do this:

$text = preg_replace_callback($reg_exUrl,function($m) {
    if( preg_match("/\.(?:jpe?g|png|gif)$/i",$m[0])) {
        return "<img src='".$m[0]."' />";
    }
    else {
        return "<a href='".$m[0]."' rel='nofollow'>".$m[0]."</a>";
    }
},$text);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.