Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: Delete specific index from string?

Tags:

string

php

I want to be able to specify an index in a string and remove it.

I have the following:

"Hello World!!"

I want to remove the 4th index (o in Hello). Here would be the end result:

"Hell World!!"

I've tried unset(), but that hasn't worked. I've Googled how to do this and that's what everyone says, but it hasn't worked for me. Maybe I wasn't using it right, idk.

like image 342
Rob Avery IV Avatar asked Feb 23 '13 03:02

Rob Avery IV


2 Answers

This is a generic way to solve it:

$str = "Hello world";
$i = 4;
echo substr_replace($str, '', $i, 1);

Basically, replace the part of the string before from the index onwards with the part of the string that's adjacent.

See also: substr_replace()

Or, simply:

substr($str, 0, $i) . substr($str, $i + 1)
like image 115
Ja͢ck Avatar answered Nov 15 '22 16:11

Ja͢ck


This php specific of working with strings also bugged me for a while. Of course natural solution is to use string functions or use arrays but this is slower than directly working with string index in my opinion. With the following snippet issue is that in memory string is only replaced with empty � and if you have comparison or something else this is not good option. Maybe in future version we will get built in function to remove string indexes directly who knows.

$string = 'abcdefg';
$string[3] = '';
var_dump($string);
echo $string;
like image 36
tslid Avatar answered Nov 15 '22 14:11

tslid