views:

348

answers:

3

Hi

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?

for example ..

$input = "abcdef";
$pad_str = "@";

so if I give insert index 3, it inserts "@" after first 3 left most characters and $input becomes "abc@def".

thanks

A: 

you need:

substr($input, 0, 3).$pad_str.substr($input, 3)
SilentGhost
yes it works .. but using $newstring = substr_replace($orig_string, $insert_string, $position, 0);
Wbdvlpr
huh? what/who is using `substr_replace`?
SilentGhost
A: 

Bah, I misread the question. You want a single insert, not insert every X characters. Sorry.

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) % 3 == 0) {
        $strip = true;
    }
    $tmp = preg_replace("/(.{$cnt})/","$1$wha", $str);
    if ($strip) {
        $tmp = substr($tmp,0,-1);
    }
    return $tmp;
}

?>
vinko@mithril:~$ php re.php
123@123@123
123@12
123$12
Vinko Vrsalovic
yes single insert only .. thnks for your answer .. and just noticed another answers as well
Wbdvlpr
+3  A: 

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.

Try:

$newstring = substr_replace($orig_string, $insert_string, $position, 0);

via: http://www.krizka.net/2007/12/29/how-to-insert-a-string-into-another-string-in-php/

databyss
substr_replace("123123123","@",3,0) is "123@123123"
Vinko Vrsalovic
Which is what the OP asked :-)
Vinko Vrsalovic
yes this is the function I wanted to look at .. thanks.
Wbdvlpr