php正则表达式从字符串获取第一个URL
我在PHP中使用以下正则表达式从字符串中获取URLphp正则表达式从字符串获取第一个URL,php,regex,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]); $URL返回所有URL。如何仅返回第一个URL?在这种情况下,http
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]);
$URL
返回所有URL。如何仅返回第一个URL?在这种情况下,http://google.com
我试图在不使用foreach循环的情况下实现这一点
^.*?(https?\:\/\/[^\" ]+)
试试这个。抓取捕获或组。参见演示
试试这个。抓取捕获或组。参见演示
使用而不是preg\u match\u all使用而不是preg\u match\u all只需打印第0个索引即可
$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]);
输出:
http://google.com
只需打印第0个索引
$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]);
输出:
http://google.com
根据报告:
preg_match_all-执行全局正则表达式匹配
因为您只需要一个,所以您应该使用:
执行正则表达式匹配
收益率:
http://google.com
根据报告:
preg_match_all-执行全局正则表达式匹配
因为您只需要一个,所以您应该使用:
执行正则表达式匹配
收益率:
http://google.com
preg\u match\u all()
有一个标志参数,可用于对结果排序。变量$matches
所在的参数是您的结果,应该列在该数组中
$matches[0][0];//is your first item.
$matches[0][1];//is your second
最好使用preg\u match()
而不是preg\u match\u all()
以下是有关标记的preg\u match\u all()
文档 preg\u match\u all()
有一个标志参数,可用于对结果排序。变量$matches
所在的参数是您的结果,应该列在该数组中
$matches[0][0];//is your first item.
$matches[0][1];//is your second
最好使用preg\u match()
而不是preg\u match\u all()
以下是有关标记的
preg\u match\u all()
文档 @LalitSharma的可能副本不是一个duplicate@CyberJunkie一个改进的版本应该是'~https?://[^”]+~i'
可能重复的@LalitSharma不是一个duplicate@CyberJunkie改进的版本应该是'~https?://[^”]+~i'