1

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
  • 20,068
  • 55
  • 141
  • 210

5 Answers5

8

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,070
  • 5
  • 71
  • 94
1

Use preg_match instead of preg_match_all

Bart Haalstra
  • 1,052
  • 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,051
  • 11
  • 52
  • 72
bashleigh
  • 7,920
  • 5
  • 26
  • 45
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
  • 65,133
  • 10
  • 87
  • 119
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
  • 166,785
  • 24
  • 204
  • 249