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

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 |


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


I explode the string at first as the url might be half way through it e.g. hello how are you www.google.com

Explode the string and use a foreach statement.

Eg:

$string = "hello how are you www.google.com";
$string = explode(" ", $string);
foreach ($string as $word){
  if ( (strpos($word, "http://") === 0) || (strpos($word, "www.") === 0) ){
  // Code you want to excute if string is a link
  }
}

Note you have to use the === operator because strpos can return, will return a 0 which will appear to be false.