如何从 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;
在这里,我们可以使用 a preg_replace
,带有一个简单的表达式,可能类似于:
(.+\.com\/.+?\/).+
我们使用这个捕获组捕获我们想要的输出:
(.+\.com\/.+?\/)
然后我们滑动到字符串的末尾并将其替换为$1
.
$re = '/(.+\.com\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';
$result = preg_replace($re, $subst, $str);
echo $result;
jex.im可视化正则表达式:
对于所有域.com
与否,我们也许可以用这个表达式来解决它:
(.+\..+?\/.+?\/).+
$re = '/(.+\..+?\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';
$result = preg_replace($re, $subst, $str);
echo $result;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句