$str=':this is a applepie :) ';
Run Code Online (Sandbox Code Playgroud)
如何使用PHP,删除第一个字符:
mar*_*rio 533
该substr()功能可能会帮助您:
$str = substr($str, 1);
Run Code Online (Sandbox Code Playgroud)
字符串从0开始索引,此函数第二个参数采用cutstart.所以,让那个1,第一个字符消失了.
Hai*_*vgi 310
要从:字符串的开头删除每个字符,可以使用ltrim:
$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'
Run Code Online (Sandbox Code Playgroud)
ale*_*exn 93
使用substr:
$str = substr($str, 1); // this is a applepie :)
Run Code Online (Sandbox Code Playgroud)
Hay*_*enn 64
执行时间为3个答案:
通过更换外壳删除第一个字母
$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by ?, but ok for echo
Run Code Online (Sandbox Code Playgroud)
执行1.000.000次测试的时间:0.39602184295654秒
删除substr()的第一个字母
$str = "hello";
$str = substr($str, 1);
Run Code Online (Sandbox Code Playgroud)
执行1.000.000次测试的时间:5.153294801712秒
用ltrim()删除第一个字母
$str = "hello";
$str= ltrim ($str,'h');
Run Code Online (Sandbox Code Playgroud)
执行1.000.000次测试的时间:5.2393000125885秒
用preg_replace()删除第一个字母
$str = "hello";
$str = preg_replace('/^./', '', $str);
Run Code Online (Sandbox Code Playgroud)
执行1.000.000次测试的时间:6.8543920516968秒
Tar*_*odi 25
这是代码
$str = substr($str, 1);
echo $str;
Run Code Online (Sandbox Code Playgroud)
输出:
this is a applepie :)
Run Code Online (Sandbox Code Playgroud)
$str = substr($str, 1);
Run Code Online (Sandbox Code Playgroud)
请参阅PHP手册示例3
echo substr('abcdef', 1); // bcdef
Run Code Online (Sandbox Code Playgroud)
注意:
unset($str[0])
Run Code Online (Sandbox Code Playgroud)
将无法工作,因为你不能取消字符串的一部分: -
Fatal error: Cannot unset string offsets
Run Code Online (Sandbox Code Playgroud)
经过进一步测试后,我不建议再使用它了.当我在MySQL查询中使用更新的字符串时,它导致了一个问题,并改为substr修复问题.我想删除这个答案,但评论表明它更快,所以有人可能会使用它.您可能会发现修剪更新的字符串可以解决字符串长度问题.
有时你不需要一个功能:
$str[0] = '';
Run Code Online (Sandbox Code Playgroud)
例如:
$str = 'AHello';
$str[0] = '';
echo $str; // 'Hello'
Run Code Online (Sandbox Code Playgroud)
此方法修改现有字符串而不是创建另一个字符串.
接受的答案是:
$str = ltrim($str, ':');
Run Code Online (Sandbox Code Playgroud)
但是:当一开始有多个时会删除多个.
$str = substr($str, 1);
Run Code Online (Sandbox Code Playgroud)
将从头开始删除任何字符.
然而,
if ($str[0] === ':')
$str = substr($str, 1);
Run Code Online (Sandbox Code Playgroud)
工作得很好.
要在PHP中删除字符串的第一个字符,
$string = "abcdef";
$new_string = substr($string, 1);
echo $new_string;
Generates: "bcdef"
Run Code Online (Sandbox Code Playgroud)
您可以使用sbstr()函数
$amount = 1; //where $amount the the amount of string you want to delete starting from index 0
$str = substr($str, $amount);
Run Code Online (Sandbox Code Playgroud)