gpt4 book ai didi

php - 仅当字符串的最后一个字符为 "s"时才删除它

转载 作者:行者123 更新时间:2023-12-03 01:57:11 25 4
gpt4 key购买 nike

我正在尝试编写一个代码,如果该字符串的最后一个字母是“s”,则从特定字符串中删除最后一个字符

$字符串值

Parts
Sealless Tools
Strap

子字符串将删除最后一个字母;但是,它也会将 p 从表带上移除,这是不需要的。

substr($string,0,-1)

pregreplace 删除每个单词的最后一个 s。它将把无密封工具变成密封工具,这是不希望的。也许我可以使用不同的表达方式?

preg_replace("/s\b/", "", $string)

我搜索了谷歌,但找不到删除完整字符串的最后一个单词(仅当它是字母 s 时)的确切答案。所有结果都是针对单个单词的。

最佳答案

一些选项...

1) $string = preg_replace('/s$/', '', $string); // slight modification to yours which limits to trailing 's'

2) $string = rtrim($string, 's'); // note: will remove 1+

3) $string = substr($string, -1) === 's' ? substr($string, 0, -1) : $string;

4) $string = $string[-1] === 's' ? substr($string, 0, -1) : $string; // php 7.1+ only

关于php - 仅当字符串的最后一个字符为 "s"时才删除它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48792025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com