php正则表达式找到空间之前的内容

时间:2011-07-09 09:42:46

标签: php regex

如何找到一个只能找到那些年份网址的正则表达式,

基本上在网址后面总是有一个空格。

$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);';

5 个答案:

答案 0 :(得分:3)

如果所有字符串看起来都那么简单:

/^([^ ]*)/

答案 1 :(得分:2)

您可以使用explode来提高效率。

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

答案 2 :(得分:1)

尝试:

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

这应该匹配所有以http开头的字符串,直到找到空格

答案 3 :(得分:1)

我认为这会解决问题:

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

答案 4 :(得分:1)

我会去:

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

以防var不以http

开头

此外,为了测试它,你可以尝试这个正则表达式(或任何其他):

(http:[^ ]+)

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