删除字符串的一部分,但仅当它位于字符串末尾时

问题描述 投票:0回答:9

我需要删除字符串的子字符串,但仅限于该子字符串位于字符串末尾时。

例如,删除以下字符串末尾的“string”:

"this is a test string" ->  "this is a test "
"this string is a test string" - > "this string is a test "
"this string is a test" -> "this string is a test"

有什么想法吗?可能是某种 preg_replace,但是如何??

php string replace preg-replace
9个回答
140
投票

您会注意到

$
字符的使用,它表示字符串的结尾:

$new_str = preg_replace('/string$/', '', $str);

如果字符串是用户提供的变量,最好首先运行它:

preg_quote

如果子字符串包含特殊字符,则使用正则表达式可能会失败。

37
投票

$remove = $_GET['remove']; // or whatever the case may be $new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);

我为字符串的左右修剪编写了这两个函数:

13
投票

我想你可以使用


2
投票

http://tr.php.net/preg_replace

PHP 8 版本


1
投票

如果你不介意性能并且字符串的部分只能放在字符串的末尾,那么你可以这样做:

0
投票

@Skrol29的答案是最好的,但这里它是函数形式并使用三元运算符:

0
投票

使用 PHP 8,代码可以更简单。

0
投票

© www.soinside.com 2019 - 2024. All rights reserved.