【问题标题】:PHP strstr - The reverse methodPHP strstr - 反向方法
【发布时间】:2014-12-14 17:53:07
【问题描述】:

我希望获得与 php strstr 命令相同的确切结果(当它设置为 true 时),但顺序相反。

我知道我可以简单地反转字符串并使用 strstr 然后再次反转它

但我想知道该任务是否有任何内部 php 命令。

<?php

$myString = 'We don\'t need no education';

echo strstr($myString, ' ', true);

/*
 * output :
 * We
 *
 * I'm expecting to get :
 * education
 *
 */

exit;

?>

非常简单!

【问题讨论】:

    标签: php string echo trim strstr


    【解决方案1】:

    你有函数strrchr

    $myString = 'We don\'t need no education';
    
    echo strrchr($myString, ' ');
    // output : ' education'
    
    echo substr(strrchr($myString, ' '), 1);
    // output : 'education'
    

    【讨论】:

    • 这个答案有一定的误导性。 strrchr不是相反的strstr。正如official documentation 所述,strrchr 搜索字符串中最后出现的 character,而不是任何字符串。如果传递给strrchr 的指针包含多个字符,则仅使用第一个字符。幸运的是,因为 OP 只搜索一个字符,所以这在这里奏效了。
    • @Neonit 删除了误导部分
    【解决方案2】:

    来自http://php.net/manual/en/function.strstr.php#103577(在 cmets 中)

    function rstrstr($haystack,$needle)
    {
        return substr($haystack, 0, strpos($haystack, $needle));
    }
    

    作者:丹尼斯·T·卡普兰

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

         $myString = 'This is a string';
         $words = explode(' ', $myString);
         $lastWord = array_pop($words);
      

      将其包装在一个函数中

      function lastWord($string) {
         return array_pop(explode(' ', $string));
      }
      

      这对您有进一步帮助吗?

      【讨论】:

      • array_pop 期望参数是对它可以操作的数组的引用......所以在某些版本的 php 中它不会接受表达式,你必须声明一个变量。跨度>
      【解决方案4】:

      使用 str :

      $basename = strrev(substr(strchr(strrev($postfile_name),'.'),1)); 
      //test.php will return test
      
      $ext = strrchr( $postfile_name, '.' ); 
      //test.php will return .php
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-05
        • 1970-01-01
        • 2021-09-12
        • 2023-04-03
        • 2011-11-27
        • 1970-01-01
        • 2015-06-03
        相关资源
        最近更新 更多