如何获得URL的一部分?
How to get part of a URL?
我如何从 url 中删除除基础 url 和第一部分之外的所有部分。零件数量不确定。基数 url 是可变的。我尝试了一些正则表达式但徒劳无功。
$url = http://www.example.com/part1/part2/part3/part4;
base_url = parse_url($url, PHP_URL_HOST); // Outputs www.example.com
$desired_output = http://www.example.com/part1;
这里我们可以用一个preg_replace
,用一个简单的表达式,可能类似于:
(.+\.com\/.+?\/).+
我们使用此捕获组捕获所需输出的位置:
(.+\.com\/.+?\/)
然后我们滑动到字符串的末尾并将其替换为 </code>。</p>
<h3>测试</h3>
<pre><code>$re = '/(.+\.com\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '';
$result = preg_replace($re, $subst, $str);
echo $result;
DEMO
正则表达式电路
jex.im 可视化正则表达式:
对于所有域 .com
与否,我们也许可以用这个表达式来解决它:
(.+\..+?\/.+?\/).+
测试
$re = '/(.+\..+?\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '';
$result = preg_replace($re, $subst, $str);
echo $result;
Demo
我如何从 url 中删除除基础 url 和第一部分之外的所有部分。零件数量不确定。基数 url 是可变的。我尝试了一些正则表达式但徒劳无功。
$url = http://www.example.com/part1/part2/part3/part4;
base_url = parse_url($url, PHP_URL_HOST); // Outputs www.example.com
$desired_output = http://www.example.com/part1;
这里我们可以用一个preg_replace
,用一个简单的表达式,可能类似于:
(.+\.com\/.+?\/).+
我们使用此捕获组捕获所需输出的位置:
(.+\.com\/.+?\/)
然后我们滑动到字符串的末尾并将其替换为 </code>。</p>
<h3>测试</h3>
<pre><code>$re = '/(.+\.com\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '';
$result = preg_replace($re, $subst, $str);
echo $result;
DEMO
正则表达式电路
jex.im 可视化正则表达式:
对于所有域 .com
与否,我们也许可以用这个表达式来解决它:
(.+\..+?\/.+?\/).+
测试
$re = '/(.+\..+?\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '';
$result = preg_replace($re, $subst, $str);
echo $result;