Yaniv Golan
Yaniv Golan

Reputation: 982

isolating a match with regular expressions and PHP

still struggling with regex :) i have this code:

$link = '/\bhttp:\/\/.+\..+[\/\w]?\b/i';
$match = array();
if (preg_match($link, 'http://bit.ly/hghjK6 bla bla',&$match))
{
    echo 'match'.'</br>';
    print_r($match);
}

as i'm trying to extract only the URL from the string i cant isolate it and the value inserted into $match always contain the "bla bla" taht follows the URL in my string what is the regex needed to only match the URL and nothing else that comes after? Thanks

Upvotes: 1

Views: 84

Answers (1)

mauris
mauris

Reputation: 43619

$r = '`(\s|\A)(http|https|ftp|ftps)://(.*?)(\s|\n|[,.?!](\s|\n)|$)`ism'; // regex to match a URL

$i = preg_match_all($r, $str, $m, PREG_SET_ORDER);
if($i){
  foreach($m as $set){
    // each $set in $m is a group of match
    // complete URL is
    echo $set[2].'://'.$set[3];
  } 
}

this matches ALL the URL in a text.

Upvotes: 1

Related Questions