php 如何在另一个字符串中插入一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1372737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a string inside another string?
提问by TigerTiger
Just looked at function
只看功能
str_pad($input, $pad_length, $pad_str, [STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH])
which helps to pad some string on left, right or on both sides of a given input.
这有助于在给定输入的左侧、右侧或两侧填充一些字符串。
Is there any php function which I can use to insert a string inside an input string?
是否有任何 php 函数可用于在输入字符串中插入字符串?
for example ..
例如 ..
$input = "abcdef";
$pad_str = "@";
so if I give insert index 3, it inserts "@"after first 3 left most characters and $inputbecomes "abc@def".
所以如果我给插入索引 3,它会"@"在前 3 个最左边的字符之后插入并$input变成"abc@def".
thanks
谢谢
回答by databyss
You're looking for a string insert, not a padding.
您正在寻找字符串插入,而不是填充。
Padding makes a string a set length, if it's not already at that length, so if you were to give a pad length 3 to "abcdef", well it's already at 3, so nothing should happen.
填充使字符串具有固定长度,如果它还没有达到那个长度,那么如果你给“abcdef”一个填充长度 3,那么它已经是 3,所以什么都不应该发生。
Try:
尝试:
$newstring = substr_replace($orig_string, $insert_string, $position, 0);
回答by SilentGhost
you need:
你需要:
substr($input, 0, 3).$pad_str.substr($input, 3)
回答by Vinko Vrsalovic
Bah, I misread the question. You want a single insert, not insert every X characters. Sorry.
呸,我误读了这个问题。您想要单个插入,而不是插入每个 X 字符。对不起。
I'll leave it here so it's not wasted.
我会把它留在这里,以免浪费。
You can use regular expressions and some calculation to get your desired result (you probably could make it with pure regexp, but that would be more complex and less readable)
您可以使用正则表达式和一些计算来获得所需的结果(您可能可以使用纯正则表达式来实现,但这会更复杂且可读性更低)
vinko@mithril:~$ more re.php
<?php
$test1 = "123123123";
$test2 = "12312";
echo puteveryXcharacters($a,"@",3);
echo "\n";
echo puteveryXcharacters($b,"@",3);
echo "\n";
echo puteveryXcharacters($b,"$",3);
echo "\n";
function puteveryXcharacters($str,$wha,$cnt) {
$strip = false;
if (strlen($str) % $cnt == 0) {
$strip = true;
}
$tmp = preg_replace('/(.{'.$cnt.'})/',"$wha", $str);
if ($strip) {
$tmp = substr($tmp,0,-1);
}
return $tmp;
}
?>
vinko@mithril:~$ php re.php
123@123@123
123@12
123

