【问题标题】:search for a substring which returns true if it is at the end搜索一个子字符串,如果它在末尾则返回 true
【发布时间】:2013-08-28 05:34:06
【问题描述】:

我想在 php 中搜索一个子字符串,以便它位于给定字符串的末尾。 例如 在字符串'abd def'上,如果我搜索def,它会在最后,所以返回true。但是如果我搜索 abd 它将返回 false ,因为它不在末尾。

有可能吗?

【问题讨论】:

  • Is it possible? 是的。

标签: php substring


【解决方案1】:

您可以为此使用preg_match

$str = 'abd def';
$result = (preg_match("/def$/", $str) === 1);
var_dump($result);

【讨论】:

    【解决方案2】:

    另一种不需要用分隔符或正则表达式分割的方法。这会测试最后的x 字符是否等于测试字符串,其中x 等于测试字符串的长度:

    $string = "abcdef";
    $test = "def";
    
    if(substr($string, -(strlen($test))) === $test)
    {
        /* logic here */
    }
    

    【讨论】:

      【解决方案3】:

      假设整个单词:

      $match = 'def';
      $words = explode(' ', 'abd def');
      
      if (array_pop($words) == $match) {
        ...
      }
      

      或者使用正则表达式:

      if (preg_match('/def$/', 'abd def')) {
        ...
      }
      

      【讨论】:

        【解决方案4】:

        这个答案应该是完全可靠的,无论是完整的单词还是其他任何东西

        $match = 'def';
        $words = 'abd def';
        
        $location = strrpos($words, $match); // Find the rightmost location of $match
        $matchlength = strlen($match);       // How long is $match
        
        /* If the rightmost location + the length of what's being matched
         * is equal to the length of what's being searched,
         * then it's at the end of the string
         */
        if ($location + $matchlength == strlen($words)) {
            ...
        }
        

        【讨论】:

          【解决方案5】:

          请看strrchr()函数。试试这样

          $word   = 'abcdef';
          $niddle = 'def';
          if (strrchr($word, $niddle) == $niddle) {
              echo 'true';
          } else {
              echo 'false';
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-11
            • 1970-01-01
            • 2015-05-13
            • 1970-01-01
            • 1970-01-01
            • 2020-07-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多