I have the following string examples:
$text = 'Hello world. '; // true
$text = 'Hello world? '; // true
$text = 'Hello world! '; // true
$text = 'Hello world. '; // true
$text = 'Hello world.'; // true
$text = 'Hello world '; // false
$text = 'Hello world'; // false
$text = 'Hello world-'; // false
If string ends with .
or ?
or !
, then return true, otherwise, return false.
What's the best approach to this?
You can use substr
, rtrim
and strpos
for this, like this:
$result = strpos("!?.", substr(rtrim($text), -1)) !== false;
This will set $result
to true or false as you have indicated.
Assuming you're asking how you can test what the last character of the string is, you can use substr()
.
You can write an if
statement like this:
<?php
// Test if the last character in the string is '!'.
if (substr($text, -1) === '!') {
return true;
}
If you want to remove the blank spaces at the end of the string, you can use $text = trim($text)
first.
If you want to test all the examples, you can use in_array()
with an array containing all the characters you want to test.
if (in_array(substr(trim($text), -1), array('!', '.', '?', )) {
return true;
}
Use preg_match to find those special string endings.
$text = array();
$text[] = 'Hello world. '; // true
$text[] = 'Hello world? '; // true
$text[] = 'Hello world! '; // true
$text[] = 'Hello world. '; // true
$text[] = 'Hello world.'; // true
$text[] = 'Hello world '; // false
$text[] = 'Hello world'; // false
$text[] = 'Hello world-'; // false
foreach($text as $t) {
echo "'" . $t . "' " . (hasSpecialEnding($t) ? 'true' : 'false') . "
";
}
function hasSpecialEnding($text) {
return preg_match('/(\?|\.|!)[ ]*$/',$text);
}
Output:
'Hello world. ' true
'Hello world? ' true
'Hello world! ' true
'Hello world. ' true
'Hello world.' true
'Hello world ' false
'Hello world' false
'Hello world-' false
You can see the code in action here: http://sandbox.onlinephpfunctions.com/code/51d839a523b940b4b4d9440cc7011e3f2f635852
This should do it:
if(preg_match('/[.?!]\h*$/', $string)){
echo 'true';
} else {
echo 'false';
}
This is a character class, []
, allowing one of the characters inside. The $
is the end of the string. The \h*
is any amount of horizontal whitespace after the symbol and before the end of the string. If you want new lines as well to be allowed use \s*
.
Regex101 Demo: https://regex101.com/r/yS3fQ6/1
PHP Demo: https://eval.in/495500