php regex从string获取第一个URL

Cyb*_*kie 0 php regex

我在PHP中使用以下正则表达式从字符串中获取URL

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]);
Run Code Online (Sandbox Code Playgroud)

$urls返回所有网址.如何只返回第一个URL?在这种情况下http://google.com.

我试图在不使用foreach循环的情况下实现此目的.

npi*_*nti 6

根据文件:

preg_match_all - 执行全局正则表达式匹配

既然你只是一个,你应该使用preg_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];
Run Code Online (Sandbox Code Playgroud)

产量:

http://google.com
Run Code Online (Sandbox Code Playgroud)