PHP if string contains URL isolate it

后端 未结 4 1237
借酒劲吻你
借酒劲吻你 2020-12-21 22:43

In PHP, I need to be able to figure out if a string contains a URL. If there is a URL, I need to isolate it as another separate string.

For example: \"SESAC showin t

相关标签:
4条回答
  • 2020-12-21 23:19

    URLs can't contain spaces, so...

    \b(?:https?|ftp)://\S+
    

    Should match any URL-like thing in a string.

    The above is the pure regex. PHP preg_* and string escaping rules apply before you can use it.

    0 讨论(0)
  • 2020-12-21 23:21

    Something like

    preg_match('/[a-zA-Z]+:\/\/[0-9a-zA-Z;.\/?:@=_#&%~,+$]+/', $string, $matches);
    

    $matches[0] will hold the result.

    (Note: this regex is certainly not RFC compliant; it may fetch malformed (per the spec) URLs. See http://www.faqs.org/rfcs/rfc1738.html).

    0 讨论(0)
  • 2020-12-21 23:34

    this doesn't account for dashes -. needed to add -

    preg_match('/[a-zA-Z]+:\/\/[0-9a-zA-Z;.\/\-?:@=_#&%~,+$]+/', $_POST['string'], $matches);
    
    0 讨论(0)
  • 2020-12-21 23:35
    $test = "SESAC showin the Love! http://twitpic.com/1uk7fi";
    $myURL= strstr ($test, "http");
    echo $myURL; // prints http://twitpic.com/1uk7fi
    
    0 讨论(0)
提交回复
热议问题