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

后端 未结 5 1041
执念已碎
执念已碎 2020-11-30 08:12

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.

         


        
5条回答
  •  执念已碎
    2020-11-30 08:44

    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.

提交回复
热议问题