Php 自定义正则表达式以正确附加url
我正在尝试从页面源获取图像url。这是我的正则表达式Php 自定义正则表达式以正确附加url,php,regex,Php,Regex,我正在尝试从页面源获取图像url。这是我的正则表达式 <?php $url='http://www.biznessapps.com'; $data = file_get_contents($url); $logo = get_logo($data); echo $logo; function get_logo($html) { //preg_match_all('', $html, $matches);
<?php
$url='http://www.biznessapps.com';
$data = file_get_contents($url);
$logo = get_logo($data);
echo $logo;
function get_logo($html)
{
//preg_match_all('', $html, $matches);
//preg_match_all('~\b((\w+ps?://)?\S+(png|jpg))\b~im', $html, $matches);
if(preg_match_all('/\bhttps?:\/\/\S+(?:png|jpg)\b/', $html, $matches))
{
echo "First";
return $matches[0][0];
}
else
{
if(preg_match_all('~\b((\w+ps?://)?\S+(png|jpg))\b~im', $html, $matches))
{
echo "Second";
return $matches[0][0];
}
else
return null;
}
}
?>
对于某些url,如:http://www.biznessapps.com
regex给出结果/frontend/images/logo.png
。这是图像url的子文件夹路径
我应该使用什么样的验证,以便如果有指向图像的子文件夹路径,它应该转换为绝对图像url,即http://www.biznessapps.com/frontend/images/logo.png
适用于上述情况
在某些情况下,用户输入url,如http://www.biznessapps.com/
因此,如果我用主url直接附加/frontend/images/logo.png
,那么它将转换为http://www.biznessapps.com//frontend/images/logo.png
这又错了
有人能建议改变regex来摆脱这个问题吗
我应该使用什么样的验证,以便若有指向图像的子文件夹路径,它应该转换为绝对图像url
您希望使用php库将相对URL转换为绝对URL
下面是一个示例代码:
require('url_to_absolute.php');
echo url_to_absolute('http://www.biznessapps.com/', '/frontend/images/logo.png');
url\u to\u absolute:失败时返回false,否则返回绝对url。如果$relativeUrl是一个有效的绝对url,则返回它时不会进行任何修改
首先,你怎么能假设你找到的第一个图像url就是你正在寻找的图像?@CasimiritHippolyte:我不是在寻找任何特定的图像。那一页上的任何图片对我来说都足够了