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;
}
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).
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.
echo substr("abcdef", -1); // returns "f"
http://php.net/manual/en/function.substr.php
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