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

后端 未结 5 1036
执念已碎
执念已碎 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:27

    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

    0 讨论(0)
  • 2020-11-30 08:29

    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 |

    0 讨论(0)
  • 2020-11-30 08:32

    I used this below which allows you to detect url's anywhere in a string. For my particular application it's a contact form to combat spam so no url's are allowed. Works very well.

    Link to resource: https://css-tricks.com/snippets/php/find-urls-in-text-make-links/

    My implementation;

    <?php
    // Validate message
    if(isset($_POST['message']) && $_POST['message'] == 'Include your order number here if relevant...') {
    $messageError = "Required";
    } else {
    $message = test_input($_POST["message"]);
    }
    if (strlen($message) > 1000) {
    $messageError = "1000 chars max";
    }
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    if (preg_match($reg_exUrl, $message)) {
    $messageError = "Url's not allowed";
    }
    
    // Validate data
    function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
    }
    ?>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 08:44

    Try implode($myarray, '').strstr("www.")==0. That implodes your array into one string, then checks whether www. is at the beginning of the string (index 0).

    0 讨论(0)
提交回复
热议问题