在php的官网上看到的parse_url()函数的替代方案。结果和parse_url()函数差不多,是使用正则实现的。
URI 是 Web上可用的每种资源 - HTML文档、图像、视频片段、程序等 - 由一个通用资源标志符(Uniform Resource Identifier, 简称"URI")进行定位。 对象分组:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? 12 3 4 5 6 7 8 9
测试代码如下:
<?php
$search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
$url = 'http://www.bkjia.com/pub/ietf/uri/#Gonn';
$url = trim($url);
preg_match_all($search, $url ,$rr);
printf("<p>输出URL数据为:</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2284" title="Insou AI"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/68b6b92f7dac5391.png" alt="Insou AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2284" title="Insou AI">Insou AI</a>
<p>Insou AI 是一款强大的人工智能助手,旨在帮助你轻松创建引人入胜的内容和令人印象深刻的演示。</p>
</div>
<a href="/ai/2284" title="Insou AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><pre class="brush:php;toolbar:false;">%s\n",var_export( $rr ,TRUE));
/*
各分组如下
$1 = http:
$2 = http
$3 = //www.bkjia.com
$4 = www.bkjia.com
$5 = /pub/ietf/uri/
$6 = 上面的正则表达式可以获取URL中的任何一部分,下面的代码则简单一些:
<?php
// 从 URL 中取得主机名
preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.bkjia.com/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>










