Question

I'm doing a forum and i got a function from the internet that makes links from text, but i wanted it to ignore youtube links for example http://www.youtube.com/....

this is the code:

function makeLinks($str) {
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$urls = array();
$urlsToReplace = array();
if(preg_match_all($reg_exUrl, $str, $urls)) {
    $numOfMatches = count($urls[0]);
    $numOfUrlsToReplace = 0;
    for($i=0; $i<$numOfMatches; $i++) {
        $alreadyAdded = false;
        $numOfUrlsToReplace = count($urlsToReplace);
        for($j=0; $j<$numOfUrlsToReplace; $j++) {
            if($urlsToReplace[$j] == $urls[0][$i]) {
                $alreadyAdded = true;
            }
        }
        if(!$alreadyAdded) {
            array_push($urlsToReplace, $urls[0][$i]);
        }
    }
    $numOfUrlsToReplace = count($urlsToReplace);
    for($i=0; $i<$numOfUrlsToReplace; $i++) {
        $str = str_replace($urlsToReplace[$i], "<a href=\"".$urlsToReplace[$i]."\">".$urlsToReplace[$i]."</a> ", $str);
    }
    return $str;
} else {
    return $str;
}
}
Was it helpful?

Solution

Try something like this:

if (preg_match('/youtube.com/i', strtolower($str))) {
    return $str;
}

Add this after function makeLinks($str) {


Usage:

var_dump(makeLinks('http://www.youtube.com'));
var_dump(makeLinks('http://www.test.com'));

Outputs:

string 'http://www.youtube.com' (length=22)

string '<a href="http://www.test.com">http://www.test.com</a> ' (length=54)

OTHER TIPS

Look to see if $urls[0][$i] does not match youtube before adding it to the array of urls to turn into links. For example, replace this snippet:

if(!$alreadyAdded) {
    array_push($urlsToReplace, $urls[0][$i]);
}

With this:

if(!$alreadyAdded) {
    if (!preg_match('/youtu\.?be/i', $urls[0][$i])) {
        array_push($urlsToReplace, $urls[0][$i]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top