【问题标题】:Check if any array values are present at the end of a string检查字符串末尾是否存在任何数组值
【发布时间】:2011-06-05 15:03:39
【问题描述】:

我正在尝试测试一个字符串是否由多个单词组成,并且是否在其末尾具有来自数组的任何值。以下是我到目前为止所拥有的。我被困在如何检查字符串是否比正在测试的数组值长并且它是否存在于字符串的末尾。

$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;
    }
}

【问题讨论】:

    标签: php arrays if-statement compare


    【解决方案1】:

    字符串结尾是指最后一个单词吗?你可以使用 preg_match

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

    【讨论】:

    • 这很好用!我添加了忽略大小写,但这很简单并且可以完成工作。 if (preg_match('~/?Wizard\??$~i', $string)) {
    【解决方案2】:

    我想你想要这样的东西:

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

    如果它必须是一个任意数组(而不是包含您在问题中提供的“向导”字符串的数组),您可以动态构造正则表达式:

    $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'
    

    【讨论】:

    • 谢谢你,关于任意数组的第二部分将有助于我在不久的将来需要做的事情。
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2013-11-12
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多