Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract URL's from a string using PHP [duplicate]

Tags:

url

php

How can we use PHP to identify URL's in a string and store them in an array?

Cannot use the explode function if the URL contains a comma, it wont give correct results.

like image 863
Azraar Azward Avatar asked Apr 12 '16 05:04

Azraar Azward


2 Answers

REGEX is the answer for your problem. Taking the Answer of Object Manipulator.. all it's missing is to exclude "commas", so you can try this code that excludes them and gives 3 separated URL's as output:

$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";

preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $string, $match);

echo "<pre>";
print_r($match[0]); 
echo "</pre>";

and the output is

Array
(
    [0] => http://google.com
    [1] => https://www.youtube.com/watch?v=K_m7NEDMrV0
    [2] => https://instagram.com/hellow/
)
like image 67
aampudia Avatar answered Oct 27 '22 09:10

aampudia


please try to use below regex

$regex = '/https?\:\/\/[^\",]+/i';
preg_match_all($regex, $string, $matches);
echo "<pre>";
print_r($matches[0]); 

Hope this will work for you

like image 33
JiteshNK Avatar answered Oct 27 '22 10:10

JiteshNK