若字符串以这些字符结尾,则


If string ends with these characters, then

我有以下字符串示例:

$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

如果字符串以.?!结尾,则返回true,否则返回false。

对此最好的方法是什么?

假设您询问如何测试字符串的最后一个字符是什么,则可以使用substr()

你可以这样写一个if语句:

<?php
// Test if the last character in the string is '!'.
if (substr($text, -1) === '!') {
    return true;
}

如果要删除字符串末尾的空格,可以先使用$text = trim($text)

如果要测试所有示例,可以将in_array()与包含要测试的所有字符的数组一起使用。

if (in_array(substr(trim($text), -1), array('!', '.', '?', )) {
    return true;
}

您可以使用substrrtrimstrpos,如下所示:

$result = strpos("!?.", substr(rtrim($text), -1)) !== false;

这将把$result设置为truefalse,如您所示。

这应该做到:

if(preg_match('/[.?!]'h*$/', $string)){
      echo 'true';
} else {
     echo 'false';
}

这是一个字符类[],允许其中一个字符。$是字符串的末尾。'h*是在符号之后和字符串末尾之前的任何数量的水平空白。如果您也希望允许使用新行,请使用's*

Regex101演示:https://regex101.com/r/yS3fQ6/1

PHP演示:https://eval.in/495500

使用preg_match查找那些特殊的字符串结尾。

$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') . "'n";
}
function hasSpecialEnding($text) {
  return preg_match('/('?|'.|!)[ ]*$/',$text);
}

输出:

'Hello world. ' true
'Hello world? ' true
'Hello world! ' true
'Hello world.   ' true
'Hello world.' true
'Hello world ' false
'Hello world' false
'Hello world-' false

您可以在此处查看正在运行的代码:http://sandbox.onlinephpfunctions.com/code/51d839a523b940b4b4d9440cc7011e3f2f635852