php 如何知道 $string 是否以 ',' 结尾?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4764859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to know if a $string ends with ','?
提问by Toni Michel Caubet
Possible Duplicate:
Find last character in a string in PHP
可能的重复:
在 PHP 中查找字符串中的最后一个字符
hi there?
你好呀?
how can i know if the last char of a $string is ',' ?
我怎么知道 $string 的最后一个字符是否是 ',' ?
thanks a lot?
多谢?
回答by ircmaxell
There are a few options:
有几个选项:
if (substr($string, -1) == ',') {
Or (slightly less readable):
或者(可读性稍差):
if ($string[strlen($string) - 1] == ',') {
Or (even less readable):
或者(甚至更难读):
if (strrpos($string, ',') == strlen($string) - 1) {
Or (even worse yet):
或者(甚至更糟):
if (preg_match('/,$/', $string)) {
Or (wow this is bad):
或者(哇,这很糟糕):
if (end(explode(',', $string)) == '') {
The take away, is just use substr($string, -1)
and be done with it. But there are many other alternatives out there...
带走,只是使用substr($string, -1)
并完成它。但是还有很多其他的选择......
回答by Floern
$string = 'foo,bar,';
if(substr($string, -1) === ','){
// it ends with ','
}
回答by Steve Dickinson
You can use regular expressions for this in PHP:
您可以在 PHP 中为此使用正则表达式:
if (preg_match("/,$/", $string)) {
#DO THIS
} else {
#DO THAT
}
This says to check for a match of a comma at the end of the $string.
这表示检查 $string 末尾的逗号匹配。
回答by GolezTrol
if (substr($str, -1) === ',')
{
echo 'it is';
}
回答by mario
For the micro optimizers:
对于微优化器:
$string[strlen($string)-1] == ","
回答by slier
//$str hold your string
if(substr($str, -1) ==',')
{
return true
}