【问题标题】:Get the last word of a string获取字符串的最后一个单词
【发布时间】:2013-09-07 21:40:55
【问题描述】:

我已经尝试了一些方法来完成最后一部分 我这样做了:

$string = 'Sim-only 500 | Internet 2500';
preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$ | Internet ","",$string
AND
preg_match("/[^ ]*$/","",{abo_type[1]})

第一个不起作用,第二个返回一个数组,但确实需要一个字符串。

【问题讨论】:

标签: php string


【解决方案1】:

有一个单行解决方案。

basename(str_replace(' ', '/', 'hello world'));

将返回世界

【讨论】:

    【解决方案2】:

    使用正则表达式的单行解决方案:

    preg_replace('/.*\s/', '', $string);
    

    这会抑制以空格结尾的所有内容,并且由于正则表达式总是“尽可能长地”匹配,因此它将匹配除最后一个单词之外的所有内容。 这对于使用任何“空格”字符(制表符、换行符...)也有好处。

    但最好的性能/资源消耗解决方案是:

    substr($string, strrpos($string, ' ') + 1);
    

    【讨论】:

      【解决方案3】:

      现有的解决方案都可以正常工作,但我想要一个单线。 explode() 会将句子拆分为单词,但尝试将其直接传递给 array_pop()end() 会给出“仅应通过引用传递变量”的通知。 array_slice() 救援:

      $string = 'Sim-only 500 | Internet 2500';
      echo array_slice(explode(' ', $string), -1)[0];
      

      【讨论】:

        【解决方案4】:

        如果您在句子中的最后一个单词之后,为什么不这样做呢?

        $string = '​Sim-only 500 ​| Internet 2500';
        $pieces = explode(' ', $string);
        $last_word = array_pop($pieces);
        
        echo $last_word;
        

        我不建议使用正则表达式,因为它是不必要的,除非你真的出于某种原因想要这样做。

        $string = 'Retrieving the last word of a string using PHP.';
        preg_match('/[^ ]*$/', $string, $results);
        $last_word = $results[0]; // $last_word = PHP.
        

        如果考虑到资源/效率/开销,使用substr() 方法会比这两种方法都好。

        $string = 'Retrieving the last word of a string using PHP.';
        $last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
        $last_word = substr($string, $last_word_start); // $last_word = PHP.
        

        它更快,尽管它对这样的事情并没有太大的影响。如果您经常需要知道 100,000 字串上的最后一个字,您可能应该以不同的方式处理它。

        【讨论】:

        • 那么,你会从一个 1000 个单词的句子中创建一个 1000 长度的数组来获取最后一个单词吗?
        • @Sebastian 上下文很重要,但如果是 1,000 字,是的,我可能仍然会。除非您将脚本运行数千/数百万次,否则与这种方式相比,您以另一种方式执行它所节省的时间不会超过我写此评论所花费的时间。
        • 对于我们这些只检查一次小字符串的人来说,它非常适合。谢谢。
        【解决方案5】:

        这是从字符串中获取最后一个单词的另一种方法

        $my_string = "fetch the last word from me";
         
        // Explode the string into an array
        $my_string = explode(" ", $my_string);
        
        // target the last word with end() function 
        $my_string = end($my_string);
        
        echo $my_string;
        

        结果me

        【讨论】:

          【解决方案6】:

          如果你想用 span 包裹最后一个单词:

          <?php
          /**
           * Wrap last word with span
           * @author: Elron
           * https://stackoverflow.com/questions/18612872/get-the-last-word-of-a-string
           */
          function wrap_last_word($string) {
              // Breaks string to pieces
              $pieces = explode(" ", $string);
          
              // Modifies the last word
              $pieces[count($pieces)-1] = '<span class="is-last-word">' . $pieces[count($pieces)-1] . '</span>';
          
              // Returns the glued pieces
              return implode(" ", $pieces);
          }
          
          wrap_last_word('hello this is wrapped');
          // returns this:
          // hello this is <span class="is-last-word">wrapped</span>
          

          【讨论】:

            【解决方案7】:

            你可以使用通用函数从字符串中获取最后一个单词

            public function get_last_words($amount, $string)
            {
                $amount+=1;
                $string_array = explode(' ', $string);
                $totalwords= str_word_count($string, 1, 'àáãç3');
                if($totalwords > $amount){
                    $words= implode(' ',array_slice($string_array, count($string_array) - $amount));
                }else{
                    $words= implode(' ',array_slice($string_array, count($string_array) - $totalwords));
                }
            
                return $words;
            }
            $string = '​Sim-​only 500 | Internet 2500​';
            echo get_last_words(1,  $string );
            

            【讨论】:

              【解决方案8】:

              这应该适合你:

              $str = "fetch the last word from me";
              $last_word_start = strrpos ( $str , " ") + 1;
              $last_word_end = strlen($str) - 1;
              $last_word = substr($str, $last_word_start, $last_word_end);
              

              【讨论】:

              • 这里不需要$last_word_end。当substr 的第三个参数被省略时,该函数将获取从$last_word_start 到字符串末尾的所有内容。如果你坚持要它,那么它应该是$last_word_end = strlen($str) - $last_word_start(你的通常不会给出错误的结果,但它是没有意义的;如果字符串不包含空格就会出错)。
              【解决方案9】:

              这取决于您尝试做什么(从您的描述中很难理解)但是要从字符串中获取最后一个单词,您可以这样做:

              $split = explode(" ", $string);
              
              echo $split[count($split)-1];
              

              更多信息请参见How to obtain the last word of a string

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-02-14
                • 2011-06-08
                • 1970-01-01
                • 2022-12-18
                相关资源
                最近更新 更多