How to match a pattern and store it in an array using preg_match

I want to search for url in a string and store them in an array.
This seems easy, but I can't seem to find a way to do it. I think it might be similar to using preg_replace?

$myarray = preg_replace(
"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",
 null, $input)

      

For example, my input line is

$input = "    
    blah blah blah https://www.google.com 
    blah blah blah https://www.yahoo.com
    blah blah blah http://stackoverflow.com"

      

Finally, the result should be the values โ€‹โ€‹of the three references matched in the array.

$myarray[0] = "https://www.google.com"
$myarray[1] = "https://www.yahoo.com"
$myarray[2] = "https://stackoverflow.com"

      

I hope you understand my desire and are sorry if something is not clear.

+3


source to share


1 answer


Use preg_match instead of preg_replace

preg_match(
"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",
 $input, $matches);

print_r($matches[0]);

      

Update:



preg_match will result in a single match.

To fit all use cases preg_match_all

+2


source







All Articles