检查字符串末尾是否存在任何数组值


Check if any array values are present at the end of a string

我正在测试一个由多个单词组成的字符串,它的末尾是否有数组中的任何值。我一直纠结于如何检查字符串是否比正在测试的数组值长,以及它是否存在于字符串的末尾。

$words = trim(preg_replace('/'s+/',' ', $string));
$words = explode(' ', $words);
$words = count($words);
if ($words > 2) {
    // Check if $string ends with any of the following
    $test_array = array();
    $test_array[0] = 'Wizard';
    $test_array[1] = 'Wizard?';
    $test_array[2] = '/Wizard';
    $test_array[4] = '/Wizard?';
    // Stuck here
    if ($string is longer than $test_array and $test_array is found at the end of the string) {
      Do stuff;
    }
}

字符串的末尾是指最后一个单词吗?您可以使用preg_match

preg_match('~/?Wizard'??$~', $string, $matches);
echo "<pre>".print_r($matches, true)."</pre>";

我想你想要这样的东西:

if (preg_match('/'/?Wizard'??$/', $string)) { // ...

如果它必须是一个任意数组(而不是包含您在问题中提供的"向导"字符串的数组),您可以动态构建regex:

$words = array('wizard', 'test');
foreach ($words as &$word) {
    $word = preg_quote($word, '/');
}
$regex = '/(' . implode('|', $words) . ')$/';
if (preg_match($regex, $string)) { // ends with 'wizard' or 'test'

这是你想要的吗(不能保证正确性,不能测试)?

foreach( $test_array as $testString ) {
  $searchLength = strlen( $testString );
  $sourceLength = strlen( $string );
  if( $sourceLength <= $searchLength && substr( $string, $sourceLength - $searchLength ) == $testString ) {
    // ...
  }
}

我想知道一些正则表达式在这里是否更有意义。