Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

Possible Duplicate:
Find last character in a string in PHP

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

like image 220
Toni Michel Caubet Avatar asked Jan 21 '11 23:01

Toni Michel Caubet


People also ask

How do you check if a character is repeated in a string JS?

you can use . indexOf() and . lastIndexOf() to determine if an index is repeated. Meaning, if the first occurrence of the character is also the last occurrence, then you know it doesn't repeat.

How do you know when a string ends in numbers?

To check if a string ends with a number, call the test() method on a regular expression that matches one or more numbers at the end a string. The test method returns true if the regular expression is matched in the string and false otherwise.

How do you check if a string ends with another string?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

How do you check if a string ends with a substring in Java?

The Java String endsWith() method is used to check whether the string is ending with user-specified substring or not. Based on this comparison it returns the result in boolean value true if the specific suffix is matched or it returns false if the suffix does not match.


2 Answers

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

like image 185
ircmaxell Avatar answered Oct 09 '22 12:10

ircmaxell


$string = 'foo,bar,'; if(substr($string, -1) === ','){     // it ends with ',' } 
like image 34
Floern Avatar answered Oct 09 '22 13:10

Floern