Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting a url using preg_match? without http:// in the string

I was wondering how I could check a string broken into an array against a preg_match to see if it started with www. I already have one that check for http://www.

function isValidURL($url)
{
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

$stringToArray = explode(" ",$_POST['text']);

  foreach($stringToArray as $key=>$val){
  $urlvalid = isValidURL($val);
  if($urlvalid){
  $_SESSION["messages"][] = "NO URLS ALLOWED!";
  header("Location: http://www.domain.com/post/id/".$_POST['postID']);
     exit();
     }
     }

Thanks! Stefan

like image 626
Stefan P Avatar asked May 04 '10 01:05

Stefan P


2 Answers

You want something like:

%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i

this is using the | to match either http:// or www at the beginning. I changed the delimiter to % to avoid clashing with the |

like image 60
Igor Serebryany Avatar answered Oct 18 '22 19:10

Igor Serebryany


John Gruber of Daring Fireball has posted a very comprehensive regex for all types of URLs that may be of interest. You can find it here:

http://daringfireball.net/2010/07/improved_regex_for_matching_urls

like image 23
mromaine Avatar answered Oct 18 '22 20:10

mromaine