去除字符串末尾的破折号或任何特殊字符。

3

我使用以下方法将字符串中的特殊字符转换为破折号,但保留字母数字字符:

return preg_replace("![^a-z0-9]+!i", "-", $str);

然而,在某些情况下,我有这些字符串:
$str = "Hello there chubby!";

这将导致:
Hello-there-chubby-

单词末尾的破折号让我想到了一种解决方法,可以去除它。

2个回答

7
return trim(preg_replace("![^a-z0-9]+!i", "-", $str), '-');

会删除前导和尾随的破折号。


2
你可以尝试使用以下代码来去除字符串末尾的特殊字符: rtrim("Hello-there-chubby-", "-"); 或者使用以下正则表达式替换函数: preg_replace("#[^a-z0-9]+$#ims", "", "Hello-there-chubby-");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接