In this PHP tutorial, you shall learn how to check if given string ends with a punctuation using ctype_punct() function, with example programs.
PHP – Check if String Ends with Punctuation
To check if given string ends with punctuation character, get the last character of the string and pass this character to ctype_punct() built-in PHP function. ctype_punct() returns true if the character matches punctuation character, else it returns false.
The syntax of condition to check if the last character is punctuation or not is
ctype_punct($lastchar)
Examples
1. Check if String Ends with Punctuation
In this example, we will take a string, “Hello World!”, in $string variable. We will get the last character using $string[-1]. We shall then pass this last character as argument to ctype_punct() function. We can use the ctype_punct() as a condition in PHP If statement. If ctype_punct() returns true, then our string ends with punctuation.
PHP Program
<?php
$string = "Hello World!";
$lastchar = $string[-1];
if ( ctype_punct($lastchar) ) {
echo "\"{$string}\" ends with punctuation.";
} else {
echo "\"{$string}\" does not end with punctuation.";
}
?>
Output
Conclusion
In this PHP Tutorial, we learned how to check if a string ends with punctuation, using PHP built-in function ctype_punct().