0

I'm trying to get all urls from this string:

2014 urmymuse Licensed to the public under http://creativecommons.org/licenses/by/3.0/ Verify at http://ccmixter.org/files/urmymuse/47486

I tried with:

$url_str = "";
    $matches = preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#i', $str, $urls);
    if ($matches) {
       foreach ($urls as $url) {
        $urls_str = $urls_str . ' ' . $url[0];
       }
    }

But outcome is: " http://creativecommons.org/licenses/by/3.0/ /" instead of the awaited two urls. What I'm doing wrong?

3

1 Answer 1

0

The issue with your regex is that it's capturing both the URL and the following slash character.

try to use this:

$matches = preg_match_all('#\bhttps?://\S+#i', $str, $urls);

instead of:

$matches = preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#i', $str, $urls); 

This should correctly extract both URLs from the provided string.

$str = "2014 urmymuse Licensed to the public under http://creativecommons.org/licenses/by/3.0/ Verify at http://ccmixter.org/files/urmymuse/47486";
$url_str = ""; 
$matches = preg_match_all('#\bhttps?://\S+#i', $str, $urls);
print_r($urls);
if ($matches) { 
    foreach ($urls as $url) { 
        $urls_str = $url_str . ' ' . $url[0]; 
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.