Page 1 of 1

Adding a character to string

Posted: Sat Aug 19, 2006 10:07 pm
by babaloui
hi,
I know how to add string to string, but I dont know how to add a chracter to string like this:

Code: Select all

$text="hello world"
I want it to print this h_ello world

I want to add underscore as second chracter in hello word.

help me plz

Posted: Sat Aug 19, 2006 10:10 pm
by Jenk

Code: Select all

$string = 'Hello world!';
$sub1 = substr($string, 0, 1);
$sub2 = substr($string, 1);
$string = $sub1 . '_' . $sub2;
Though it is about as useful as a chocolate fireguard in 'real world' situations.

Posted: Sat Aug 19, 2006 10:15 pm
by babaloui
well thanx Jenk, it woks fine. I'm new to PHP :)

Posted: Sat Aug 19, 2006 10:41 pm
by Jenk
you can even wrap it into a function to make it a bit more useful :)

Code: Select all

<?php
function InsertChar ($string, $char, $pos = 0)
{
    if ($pos >= strlen($string)) $pos = strlen($string);
    $sub1 = substr($string, 0, $pos);
    $sub2 = substr($string, $pos);
    return $sub1 . $char . $sub2;
}

echo InsertChar('Hello World!', '_', 1);
?>