PHP: How can I remove from String the last word?

后端 未结 6 1147
轻奢々
轻奢々 2021-02-05 21:39

How can I remove, with PHP, the last word from a String?

For example the string \"Hi, I\'m Gian Marco\" would become \"Hi, I\'m Gian\".

相关标签:
6条回答
  • 2021-02-05 22:17

    You can do it with regular expression. (see answer of Ahmed Ziani.)

    However, in PHP you can also do it using some inbuilt function. see the code below

    $text = "Hi, I'm Gian Marco";
    $last_space_position = strrpos($text, ' ');
    $text = substr($text, 0, $last_space_position);
    echo $text;
    
    0 讨论(0)
  • 2021-02-05 22:17

    The regular exprerssion can cause issues when the string has special characters. Why not simply go with this:

    $input = "Hi, I'm Gian Marco";
    $output = substr($input, 0, strrpos($input, " "));
    echo $output;
    
    0 讨论(0)
  • 2021-02-05 22:24

    This code may help you :

    $str="Hi, I'm Gian Marco";
    
    $split=explode("",$str);
    $split_rem=array_pop($split);
    foreach ($split as $k=>$v)
    {
       echo $v.'';
    }
    
    0 讨论(0)
  • 2021-02-05 22:25

    The current solution is ok if you do not know the last word and the string length is short.

    In case you do know it, for instance when looping a concat string for a query like this:

            foreach ($this->id as $key => $id) {
                $sql.=' id =' . $id . ' OR ';
            }
    

    A better solution:

            $sql_chain = chop($sql_chain," OR ");
    

    Be aware that preg_replace with a regex is VERY slow with long strings. Chop is 100 times faster in such case and perf gain can be substantial.

    0 讨论(0)
  • 2021-02-05 22:28

    check this

     <?php
    $str ='"Hi, I\'m Gian Marco" will be "Hi, I\'m Gian"';
    $words = explode( " ", $str );
    array_splice( $words, -1 );
    
    echo implode( " ", $words );
    ?>
    

    source : Remove last two words from a string

    0 讨论(0)
  • 2021-02-05 22:32

    try with this :

    $txt = "Hi, I'm Gian Marco";
    $str= preg_replace('/\W\w+\s*(\W*)$/', '$1', $txt);
    echo $str
    

    out put

    Hi, I'm Gian
    
    0 讨论(0)
提交回复
热议问题