Another url check thread

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Another url check thread

Post by JKM »

Hi there,

yes - another url check thread, but I couldn't find any thread for exactly my question.

if $url starts with 'http://' or 'www.', $urlCheck should return as true, else as false;

Code: Select all

$url = 'http://test.com';    
if(preg_match('/(http:\/\/|www.)/i', $url)) {
    $urlCheck = true;
} else {
    $urlCheck = false;
}
Thanks.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Another url check thread

Post by AbraCadaver »

Works for me, though you need to escape the . in your pattern.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Another url check thread

Post by McInfo »

That pattern does not necessarily match the beginning of the string. See Anchors.

Also, you can simplify the code by replacing the if and else blocks with type casting.

Code: Select all

$result = (bool) preg_match($pattern, $subject);
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Re: Another url check thread

Post by JKM »

thanks guys, but if I want preg_match_all to check for urls and return the url, how should I do it then? If I use '/(http:\/\/|www\.)/i', it only returns http://.
Post Reply