简体   繁体   中英

How to check if url is tel: or javascript: type

i curl a URL and detect all links but i have a problem it also detect tel:, JavaScript:, Skype:, chrome:, sms: and ...

I try below code to check if URL is proper or not, but this is too long code and also not include all possibility. so i want to use regex but it not working

<?php   
if($url==''){echo 'error';}                                                 // ignore self and blank links
else if(substr($url,0,strlen('#'))==='#'){echo 'error';}                        // ignore hash-tag links
else if(substr($url,0,strlen('javascript:'))==='javascript:'){echo 'error';}   // ignore script links
else if(substr($url,0,strlen('data:'))==='data:'){echo 'error';}                // ignore base64_decoded files
else if(substr($url,0,strlen('chrome:'))==='data:'){echo 'error';}              // ignore chrome links
else if(substr($url,0,strlen('mailto:'))==='mailto:'){echo 'error';}            // ignore email links
else if(substr($url,0,strlen('tel:'))==='tel:'){echo 'error';}                  // ignore mobile calls links
else if(substr($url,0,strlen('sms:'))==='tel:'){echo 'error';}                  // ignore SMS links
else if(substr($url,0,strlen('callto:'))==='callto:'){echo 'error';}            // ignore skype calls second method links
else
{
    echo $url;
}
?>
<?php
$url=$_GET['url'];
if(preg_match('^(?:[a-z]+:)?//',$url))
{
    echo 'error';
}
else
{
    echo $url;
}
?>

I expect if URL is tel: or sms: or chrome: or something like this it should be print "error" else it should be print given URL

If you want to use preg_match you have to use delimiters .

The code in your example says if there is a match for ^(?:[az]+:)?// which will match for example a:// or http:// and will then echo error because [az]+ is a very broad match.

What you could do is use a negative lookahead (?! to assert what is directly on the right is not one of the listed options.

If that assertion passes, match any char 1+ times .+ to prevent matching an empty string.

^(?!(?:javascript|data|chrome|mailto|tel|sms|callto|mms|skype):).+$

Regex demo

For example

$url = $_GET['url'];
if (preg_match('/^(?!(?:javascript|data|chrome|mailto|tel|sms|callto|mms|skype):).+$/', $url)) {
    echo $url;
} else {
    echo 'error';
}

Check if starting with http like this:

$url = $_GET['url'];
if (preg_match('/^http/', $url)) {
    echo $url;
} else {
    echo 'error';
}

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