我需要删除字符串的子字符串,但仅限于该子字符串位于字符串末尾时。
例如,删除以下字符串末尾的“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,但是如何??
您会注意到
$
字符的使用,它表示字符串的结尾:
$new_str = preg_replace('/string$/', '', $str);
preg_quote
如果子字符串包含特殊字符,则使用正则表达式可能会失败。
$remove = $_GET['remove']; // or whatever the case may be
$new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);
我为字符串的左右修剪编写了这两个函数:
我想你可以使用
string
函数。
像这样的东西应该工作得很好:
preg_replace()
注意事项:
$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);
string
string
表示
如果你不介意性能并且字符串的部分只能放在字符串的末尾,那么你可以这样做:
@Skrol29的答案是最好的,但这里它是函数形式并使用三元运算符:
使用 PHP 8,代码可以更简单。