我有一个URL作为一个字符串的特定部分,例如:字符串插入另一个字符串
http://example.com/sub/sub2/hello/
我想另一个子文件夹添加到它用PHP,hello
之前,所以应该是这样的:
http://example.com/sub/sub2/sub3/hello/
我想过使用爆炸由斜杠的URL分开,并把最后一个前一个又一个,但我敢肯定,我在复杂了。有更容易的方法吗?
我有一个URL作为一个字符串的特定部分,例如:字符串插入另一个字符串
http://example.com/sub/sub2/hello/
我想另一个子文件夹添加到它用PHP,hello
之前,所以应该是这样的:
http://example.com/sub/sub2/sub3/hello/
我想过使用爆炸由斜杠的URL分开,并把最后一个前一个又一个,但我敢肯定,我在复杂了。有更容易的方法吗?
这应该为你工作:
(在这里,我只是把额外的文件夹放在字符串的basename()
和dirname()
之间,这样它就在最后一部分之前o ˚F您的网址)
<?php
$str = "http://example.com/sub/sub2/hello/";
$folder = "sub3";
echo dirname($str) . "/$folder/" . basename($str);
?>
输出:
http://example.com/sub/sub2/sub3/hello
这是迄今为止最好的答案,谢谢:) – PeterInvincible 2015-04-01 11:54:20
如果您的网址有这个特定的格式,你可以使用这个:
$main_url = 'http://example.com/sub/sub2/';
$end_url_part = 'hello/';
$subfolder = 'sub3/';
if (isset($subfolder)) {
return $main_url.$subfolder.$end_url_part;
} else {
return $main_url.$end_url_part;
}
谢谢你的回答! :) – PeterInvincible 2015-04-01 11:47:17
explode
,splice
,implode
:
$str = "http://example.com/sub/sub2/hello/";
$str_arr = explode('/', $str);
array_splice($str_arr, -2, 0, 'sub3');
$str_new = implode('/', $str_arr);
// http://example.com/sub/sub2/sub3/hello/
谢谢,按预期工作:) – PeterInvincible 2015-04-01 11:47:08
我是唯一一个怎么没有看到这两个字符串之间的差异? – Rizier123 2015-04-01 11:35:17
@ Rizier123我也和你在一起。 :) – 2015-04-01 11:37:45
哦,对不起,更新我的问题:) – PeterInvincible 2015-04-01 11:38:26