Php 将字符串插入另一个字符串的特定部分
我有一个URL作为字符串,例如:Php 将字符串插入另一个字符串的特定部分,php,string,Php,String,我有一个URL作为字符串,例如: http://example.com/sub/sub2/hello/ 我想在hello之前用PHP向其添加另一个子文件夹,因此它应该如下所示: http://example.com/sub/sub2/sub3/hello/ 我曾考虑过使用explode以斜杠分隔URL,并在最后一个URL之前添加另一个URL,但我敢肯定我把它复杂化了。有更简单的方法吗?如果您的url有这种特定格式,您可以使用: $main_url = 'http://example.com/
http://example.com/sub/sub2/hello/
我想在hello
之前用PHP向其添加另一个子文件夹,因此它应该如下所示:
http://example.com/sub/sub2/sub3/hello/
我曾考虑过使用explode以斜杠分隔URL,并在最后一个URL之前添加另一个URL,但我敢肯定我把它复杂化了。有更简单的方法吗?如果您的url有这种特定格式,您可以使用:
$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;
}
分解
,拼接
,内爆
:
$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/
这应该适合您: (这里我只是把额外的文件夹放在字符串的和之间,这样它就在url的最后一部分之前)
我是唯一一个看不出两个字符串之间有任何区别的人吗?@Rizier123我也同意你的看法。:)哦,对不起,伙计们,更新了我的问题:)所以现在的问题是,在哪里以及如何定义子文件夹的位置?(我的意思是,它总是在最后一个文件夹之前添加文件夹,还是每次都在第二个文件夹之后添加另一个文件夹?)我想以最简单的方式在最后一个文件夹之前添加第三个子文件夹(最后一个文件夹是
hello
)。对不起,如果不清楚的话。谢谢你的回答!:)
<?php
$str = "http://example.com/sub/sub2/hello/";
$folder = "sub3";
echo dirname($str) . "/$folder/" . basename($str);
?>
http://example.com/sub/sub2/sub3/hello