Mark Elvis
Mark Elvis

Reputation: 61

replacing first character in a string with multiple characters using its index

A string like (for example):

$s = "allo";

i wanted to replace its first character with he to become hello using the indexes, so i used

$s = "allo";
$s[0] = "he";
echo $s; 

the result i expected was hello but got hllo

is there a kind of a limit on changing the letters by indexes in a string?

Upvotes: 2

Views: 2586

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133380

In PHP a string can be formed using index on the string itself without problem but You can't use $s[0] = "he"; because this way you are trying to assing to a single location two char .. so php assign just the first .. for change both the chars you must use the replace function.

You could try using replace

 $res = str_replace($s[0], "he" ,$s );

But ass suggested by Nigel Ren this work if there only an occurrence of the $s[0] in the $s string otherwise you use a string concat and substring instead of a replace

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

When using a string as an array, you are referencing individual characters, so $s[0] is the a, trying to fit two charachters into 1 isn't going to work. The easiest way to do it is to take the new string and append the old value from the second position (I've used substr($s,1))

$s = "alalo";
$res = "he".substr($s,1);
echo $res; 

gives...

helalo

Upvotes: 2

Related Questions