idan bachar
idan bachar

Reputation: 41

php regex to find what precedes a space

How to find a regex that can find me only the url's from those vars,

basically there is a space always after the url.

$var1 = 'http://www.asdasgdst.com/thebook.html Result: chosen nickname "doodoo"; success (from first page)';

$var2 = 'http://adfhdfdfcvxn.com/blog/2008/12/28/beginnings/comment-page-1/#comment-8203 Result: chosen nickname "zvika"; success (from first page);';

$var3 = 'http://sdfsd.sdfjstestgg.com/453980.html?mode=reply Result: chosen nickname "sharon"; success; not working;';

$var4 = 'http://www.yuuyok.net/index.php?sub=community&site=posts&thread_id= Result: chosen nickname "kelly"; success (from first page);';

Upvotes: 2

Views: 92

Answers (5)

WooDzu
WooDzu

Reputation: 4866

i'd go for:

preg_match('/(http:[^ ]+)/s', $var, $arr);
$url = $arr[0];

just in case the var isn't starting with http

besides, in order to test it you can try this regex (or any other):

(http:[^ ]+)

at: http://www.regextester.com/

Upvotes: 1

sroes
sroes

Reputation: 15053

I think this will do the trick:

preg_match('~^(http://.*?) Result:~', $var1, $match);
$url = $match[1];

Upvotes: 1

Dogbert
Dogbert

Reputation: 222198

You can just use explode for this, which will be much more efficient.

$url = array_pop(explode(" ", $var1, 1));

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96266

If all the string look like that then simply:

/^([^ ]*)/

Upvotes: 3

Tudor Constantin
Tudor Constantin

Reputation: 26861

try with:

'/(^http.*?)\s/'

This should match all the strings that are starting with http until a whitespace is found

Upvotes: 1

Related Questions