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

后端 未结 6 1168
轻奢々
轻奢々 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: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.

提交回复
热议问题