Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expression match first occurrences?

Tags:

regex

php

http://someurlhere.com|http://sometexturl.com|sometexthere

i want to extract only the first url which is before the | , http://someurlhere.com

i have written regular expression

\bhttp(.*)\|\b

but its capture all the occurences of |

Thanx help is appreciated

like image 818
Fawad Avatar asked Aug 26 '26 03:08

Fawad


2 Answers

Make the .* ungreedy : .*?

\bhttp(.*?)\|\b

If you want to match only after the first | do:

\|http://(.*?)\|

with this, the url is in $1

like image 59
Toto Avatar answered Aug 28 '26 17:08

Toto


No need for regex. I see you tagged it PHP.

$boom = explode('|', 'http://someurlhere.com|sometexturl.com|sometexthere');
$url = $boom[0];
echo $url;

Output:

http://someurlhere.com

http://codepad.org/xnW0FTfA

like image 30
ohaal Avatar answered Aug 28 '26 16:08

ohaal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!