2

I'm using the following regex in PHP to grab the URLs from a string

regex = '/https?\:\/\/[^\" ]+/i';
$string = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
preg_match_all($regex, $string, $matches);
$urls = ($matches[0]);

$urls returns all the URLs. How can return only the first URL? In this case http://google.com.

I'm trying to achieve this without using a foreach loop.

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215

5 Answers5

9

According to the documentation:

preg_match_all — Perform a global regular expression match

Since you are after just one, you should be using preg_match:

Perform a regular expression match

$regex = '/https?\:\/\/[^\" ]+/i';
$string = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
preg_match($regex, $string, $matches);
echo $matches[0];

Yields:

http://google.com
npinti
  • 51,780
  • 5
  • 72
  • 96
1

Use preg_match instead of preg_match_all

Bart Haalstra
  • 1,062
  • 6
  • 11
1

preg_match_all() has a flag parameter which you can use to order the results. The parameter in which you have the variable $matches is your results and should be listed in that array.

$matches[0][0];//is your first item.
$matches[0][1];//is your second

It would be better to use preg_match() rather than preg_match_all().

Here's the documentation on preg_match_all() for your flags. Link here!

HamZa
  • 14,671
  • 11
  • 54
  • 75
bashleigh
  • 8,813
  • 5
  • 29
  • 49
0
^.*?(https?\:\/\/[^\" ]+)

Try this.Grab the capture or group.See demo.

https://regex101.com/r/pM9yO9/5

$re = "/^.*?(https?\\:\\/\\/[^\\\" ]+)/";
$str = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";

preg_match_all($re, $str, $matches);
vks
  • 67,027
  • 10
  • 91
  • 124
0

Just print the 0th index.

$regex = '/https?\:\/\/[^\" ]+/i';
$string = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
preg_match_all($regex, $string, $matches);
$urls = ($matches[0]);
print_r($urls[0]);

Output:

http://google.com
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274