简体   繁体   中英

Allow some url in regular expression

I am using below regular expression to hide website url and it's working 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 url's along with facebook.com or gmail.com

Now I want to allow some url's like facebook.com or google.com or http://gmail.com I am getting trouble to modify this expression. Please help me to sort out this problem Thank you

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM