开发者

how to know if a $string ends with ','? [duplicate]

This question alrea开发者_Python百科dy has answers here: Closed 12 years ago.

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?


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...


$string = 'foo,bar,';
if(substr($string, -1) === ','){
    // it ends with ','
}


You can use regular expressions for this in 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.


if (substr($str, -1) === ',') 
{
 echo 'it is';
}


For the micro optimizers:

$string[strlen($string)-1] == ","


See the endsWith function here:

startsWith() and endsWith() functions in PHP


//$str hold your string
if(substr($str, -1) ==',')
{
   return true
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜