PHP 将字符插入到字符串中的特定位置
PHP insert character to certain position in string
我有字符串 (link)
我想在这个字符串中插入特定字符 {s}
模式:http://i.imgur.com/filename{character}.extension
之前: http://i.imgur.com/7k8t8pC.png
之后:http://i.imgur.com/7k8t8pCs.png
你可以对substr_replace使用一些小技巧:
$newstring = substr_replace( "http://i.imgur.com/7k8t8pC.png", "s", 26, 0);
编辑,一点解释:
它允许用另一个字符串替换字符串的一部分。您传递原始字符串、要插入的字符串、起点和要替换的字符数。但是,如果您传递 0,则会将第二个字符串插入第一个字符串中的给定位置。
您可以使用 preg_replace()
:
$str = 'http://i.imgur.com/7k8t8pC.png';
echo preg_replace('/(\.png)/', 's', $str);
结果:
http://i.imgur.com/7k8t8pCs.png
或使用str_replace()
:
$str = 'http://i.imgur.com/7k8t8pC.png';
echo str_replace('.png', 's.png', $str);
结果:
http://i.imgur.com/7k8t8pCs.png
我对 post 犹豫不决,但由于您使用的是路径而不是什么:
$info = pathinfo($string);
$result = $info['dirname'] . "/" . $info['filename'] . "s." . $info['extension'];
这个怎么样:
function addstring($ch,$string){
$array = explode('/',$string);
$name = explode('.',end($array));
array_pop($array);
$new = implode('/',$array);
return $new.'/'.$name[0].$ch.'.'.$name[1];
}
var_dump(addstring('CHAR','http://i.imgur.com/7k8t8pC.png'));
我有字符串 (link)
我想在这个字符串中插入特定字符 {s}
模式:http://i.imgur.com/filename{character}.extension
之前: http://i.imgur.com/7k8t8pC.png
之后:http://i.imgur.com/7k8t8pCs.png
你可以对substr_replace使用一些小技巧:
$newstring = substr_replace( "http://i.imgur.com/7k8t8pC.png", "s", 26, 0);
编辑,一点解释: 它允许用另一个字符串替换字符串的一部分。您传递原始字符串、要插入的字符串、起点和要替换的字符数。但是,如果您传递 0,则会将第二个字符串插入第一个字符串中的给定位置。
您可以使用 preg_replace()
:
$str = 'http://i.imgur.com/7k8t8pC.png';
echo preg_replace('/(\.png)/', 's', $str);
结果:
http://i.imgur.com/7k8t8pCs.png
或使用str_replace()
:
$str = 'http://i.imgur.com/7k8t8pC.png';
echo str_replace('.png', 's.png', $str);
结果:
http://i.imgur.com/7k8t8pCs.png
我对 post 犹豫不决,但由于您使用的是路径而不是什么:
$info = pathinfo($string);
$result = $info['dirname'] . "/" . $info['filename'] . "s." . $info['extension'];
这个怎么样:
function addstring($ch,$string){
$array = explode('/',$string);
$name = explode('.',end($array));
array_pop($array);
$new = implode('/',$array);
return $new.'/'.$name[0].$ch.'.'.$name[1];
}
var_dump(addstring('CHAR','http://i.imgur.com/7k8t8pC.png'));