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

Dyl*_*lan 71 php string replace preg-replace

我需要删除字符串的子字符串,但只有当它位于字符串的END时.

例如,删除以下字符串末尾的"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"
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*per 112

你会注意到$字符的使用,它表示字符串的结尾:

$new_str = preg_replace('/string$/', '', $str);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这不应该是公认的答案。使用 preg_replace 来完成这个任务是丑陋的,逻辑错误,并且完全浪费服务器能量/时间/周期(是的,这很重要,你支付更多的托管费用,因为 10000000 个其他用户的网页使用 preg_replace 而不是 substr) (2认同)

Skr*_*l29 22

如果子字符串具有特殊字符,则使用regexp可能会失败.

以下内容适用于任何字符串:

$substring = 'string';
$str = "this string is a test string";
if (substr($str,-strlen($substring))===$substring) $str = substr($str, 0, strlen($str)-strlen($substring));
Run Code Online (Sandbox Code Playgroud)

  • 最后一点可以简单地说是`$ str = substr($ str,0,-strlen($ substring));`upvoted是正则表达式的好选择.我为我的问题找到了相同的答案.如果它符合我的目的,我会随时在`preg_*`系列上使用纯字符串函数 (9认同)
  • 一个简单而智能的解决方案,无需使用正则表达式即可解决所谓的简单问题。谢谢 (2认同)

Bas*_*Bas 9

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

/**
 * @param string    $str           Original string
 * @param string    $needle        String to trim from the end of $str
 * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
 * @return string Trimmed string
 */
function rightTrim($str, $needle, $caseSensitive = true)
{
    $strPosFunction = $caseSensitive ? "strpos" : "stripos";
    if ($strPosFunction($str, $needle, strlen($str) - strlen($needle)) !== false) {
        $str = substr($str, 0, -strlen($needle));
    }
    return $str;
}

/**
 * @param string    $str           Original string
 * @param string    $needle        String to trim from the beginning of $str
 * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
 * @return string Trimmed string
 */
function leftTrim($str, $needle, $caseSensitive = true)
{
    $strPosFunction = $caseSensitive ? "strpos" : "stripos";
    if ($strPosFunction($str, $needle) === 0) {
        $str = substr($str, strlen($needle));
    }
    return $str;
}
Run Code Online (Sandbox Code Playgroud)


Pas*_*TIN 7

我想你可以使用一个正则表达式,它会匹配string,然后是字符串的结尾,再加上preg_replace()函数.


像这样的东西应该工作得很好:

$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);
Run Code Online (Sandbox Code Playgroud)


备注:

  • string 比赛......好吧...... string
  • $字符串的结尾

有关更多信息,您可以阅读PHP手册的Pattern Syntax部分.