将字符串插入另一个字符串的特定部分


Insert string into specific part of another string

我有一个URL作为字符串,例如:

http://example.com/sub/sub2/hello/

我想用PHP在hello之前添加另一个子文件夹,所以它应该是这样的:

http://example.com/sub/sub2/sub3/hello/

我曾想过使用爆炸来用斜杠分隔URL,并在最后一个之前添加另一个,但我很确定我把它复杂化了。有更简单的方法吗?

这应该适用于您:

(这里我只是把额外的文件夹放在字符串的basename()dirname()之间,这样它就在url的最后一部分之前)

<?php
    $str = "http://example.com/sub/sub2/hello/";
    $folder = "sub3";
    echo dirname($str) . "/$folder/" . basename($str);
?>

输出:

http://example.com/sub/sub2/sub3/hello

如果你的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;
}

explodespliceimplode:

$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/