Possible Duplicate:
Find last character in a string in PHP
How can I know if the last char of a $string is ',' ?
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.
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.
The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.
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.
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 ',' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With