12

我希望能够在字符串中指定索引并将其删除。

我有以下内容:

"Hello World!!"

我想删除第 4 个索引(o在 Hello 中)。这将是最终结果:

"Hell World!!"

我试过unset()了,但没有奏效。我已经用谷歌搜索了如何做到这一点,这是每个人都说的,但它对我没有用。也许我没有正确使用它,idk。

4

5 回答 5

20

这是解决它的通用方法:

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

基本上,将索引之前的字符串部分替换为相邻的字符串部分。

也可以看看:substr_replace()

或者,简单地说:

substr($str, 0, $i) . substr($str, $i + 1)
于 2013-02-23T03:54:30.850 回答
11
$str="Hello World";
$str1 = substr($str,0,4);
$str2 = substr($str,5,7);
echo $str1.$str2;
于 2013-02-23T03:48:13.693 回答
2

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;
于 2016-06-23T15:00:08.760 回答
0
$myVar = "Hello World!!";

$myArray = str_split($myVar);
array_splice($myArray, 4, 1);

$myVar = implode("", $myArray);

个人我喜欢处理数组。

(抱歉,我的手机上没有代码括号)

于 2013-02-23T04:02:14.337 回答
0

我认为可以创建一个函数并像这样调用它

    function rem_inx ($str, $ind)
    { 
       return substr($str,0,$ind++). substr($str,$ind);
    }

    //use
    echo rem_inx ("Hello World!!", 4);     
于 2014-01-22T10:36:55.233 回答