Operator Operator - 7 months ago 20
PHP Question

Need to have http added if not present before www

My function gets all the facebook description text from our string $FBdescription. This preg_replace does everything I need except when it finds a url like www.myurl.com in the description it places that in the href= and because it does not contain the http:// at the begining it of course causes problems when you click the link. How can this be adjusted to append the http:// if it's not there.

function fts_facebook_tag_filter($FBdescription)
//Converts URLs to Links in our Description Text
$FBdescription = preg_replace('@(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-‌​Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank">\0</a>', $FBdescription);
return $FBdescription;
}

Answer

Not best but working solution:

$FBdescription = 'BZRK Records and BZRK Black label Artists playing here More info : www.bzrk.agency https://www.facebook.com/daphne.merks/posts/988562257858538';

//Converts URLs to Links
$FBdescription = preg_replace('@(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-‌​Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank">\0</a>', $FBdescription);


$splitano = explode("www", $FBdescription);
$count = count($splitano);
$returnValue = "";

for($i=0; $i<$count; $i++) {
    if (substr($splitano[$i], -6, 5) == "href=") {
        $returnValue .= $splitano[$i] . "http://www";
    }
    else if($i < $count - 1){
        $returnValue .= $splitano[$i] . "www";
    }
    else {
        $returnValue .= $splitano[$i];
    }
}
echo $returnValue;