Allow some url in regex

I am using under regex to hide the website url and it works great.

$message_text=preg_replace("/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/", "<website hidden>", htmlspecialchars($message_text));

      

$ message_text will be a long message that will contain many urls along with facebook.com or gmail.com

Now I want to resolve some url like facebook.com or google.com or http://gmail.com I am having trouble changing this expression. Please help me figure out this problem. Thanks you

+3


source to share


1 answer


I think this should work for you:

<?php

    $message_text = "sdfhsdkklsdkjj www.facebook.com www.google.com http://gmail.com";
    echo $message_text = preg_replace_callback('/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/', 
        function ($match) {

            $allowed = array("www.facebook.com", "www.google.com");
            if(!in_array($match[1], $allowed))
                return "&#60;website hidden&#62;";

            return $match[1];
        }, htmlspecialchars($message_text));

?>

      



Output:

sdfhsdkklsdkjj www.facebook.com www.google.com <website hidden>

      

+3


source







All Articles