Adding a character to string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
babaloui
Forum Newbie
Posts: 6
Joined: Wed Feb 11, 2004 5:15 am

Adding a character to string

Post 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
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
babaloui
Forum Newbie
Posts: 6
Joined: Wed Feb 11, 2004 5:15 am

Post by babaloui »

well thanx Jenk, it woks fine. I'm new to PHP :)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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);
?>
Post Reply