我在PHP函数中有一个像'nameabc'的字符串。我检查字符串的最后三个字符是否为'abc',它应该删除它并返回剩余的字符串。这是我的情况:
$name="nameabc";
$last_char=substr($name,-4); //it returns the 'abc'
if($last_char == 'abc') //this condition does not return true
$real_name=substr($name,0,-4);
我不知道是什么问题
substr()
在示例中返回eabc
。你需要使用-3的偏移量:
$name="nameabc";
$last_char=substr($name,-3);
if($last_char == 'abc')
演示$last_char=substr($name,-4);
如果返回'abc',可能您的变量$name
有一个尾随空格。您可以使用strlen($name)
检查这一点。它将返回8而不是7。那是nameabc<space>
。因此,当您打印$last_char
时,它将被打印为abc<space>
,而您无法在屏幕上可视化该空间。这是一个很好的做法,总是trim
您的变量。
trim($name);
作为John的答案,您只需要-3
来获取最后3个字符。