Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string ends with punctuation in php?

Tags:

regex

php

I am parsing some text line by line and if a given line ends with any punctuation or a number I'd like to have a boolean return true.

Is regex the best way or should I iterate with an array of chars to match? Feels like the array would be far too big and costly...

Could someone help me with the regex if that is indeed a good way?

function ends_with_punctuation_or_num($string){
   // check if the string ends with punctuation or a number
    if (/* TODO */)
        return true;
    else
        return false;
}
like image 797
dcoffey3296 Avatar asked Oct 12 '12 12:10

dcoffey3296


3 Answers

Put this into your if-check:

preg_match("/[0-9.!?,;:]$/", $string)

That will match a digit, or any of the given punctuation characters right before the end of the string ($). Add any other punctuation characters you want to regard as a match into the character class (the square brackets).

like image 66
Martin Ender Avatar answered Nov 14 '22 22:11

Martin Ender


The unicode property for punctuation is \p{P} or \p{Punctuation} for a number it's \pN.

In php you can use:

preg_match('/[\p{P}\p{N}]$/u', $string);

This will return true if the string ends with a punctuation or a digit.

Have a look at this site.

like image 27
Toto Avatar answered Nov 14 '22 20:11

Toto


echo substr("abcdef", -1); // returns "f"

http://php.net/manual/en/function.substr.php

like image 26
Ron van der Heijden Avatar answered Nov 14 '22 21:11

Ron van der Heijden