Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
possible duplicate of Finding urls from text string via php and regex? –  Lalit Sharma Jan 28 at 13:19
    
@LalitSharma Not a duplicate –  HamZa Jan 28 at 13:31
    
@CyberJunkie an improved version would be '~https?://[^" ]+~i' –  HamZa Jan 28 at 13:32

5 Answers 5

up vote 3 down vote accepted

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
share|improve this answer

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!

share|improve this answer

Use preg_match instead of preg_match_all

share|improve this answer
^.*?(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);
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.