php: Extract URLs from String

2019-08-07 2019-12-30 00:24:21 PHP,string,array,EN

Q: How to extract URLs from a string with php ?

A: use the php function preg_match_all to acvhieve this.

example

// example string with URLs
$sContent = 'https://blog.ueffing.net, FOO BAR BLA BLA https://www.ueffing.net/, BLA BLA https://github.com/gueff';

$sPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
preg_match_all(
    $sPattern,
    $sContent,
    $aMatch, // <= saves result into $aMatch
    PREG_PATTERN_ORDER
);

a var_dump($aMatch); will then give you

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(24) "https://blog.ueffing.net"
    [1]=>
    string(24) "https://www.ueffing.net/"
    [2]=>
    string(24) "https://github.com/gueff"
  }
}

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".