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

发布于 2024-10-31 00:49:31 字数 295 浏览 2 评论 0原文

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

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

"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,但是如何?

I need to remove a substring of a string, but only when it is at the END of the string.

for example, removing 'string' at the end of the following strings :

"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"

Any idea's ? Probably some kind of preg_replace, but how??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

暖风昔人 2024-11-07 00:49:32

我想你可以使用 正则表达式,它将匹配字符串,然后字符串结尾,再加上preg_replace() 函数。

Something like this should work just fine :

$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);

Notes :

  • string 匹配...好吧...string
  • $ 表示 字符串结尾

有关更多信息,您可以阅读模式语法 PHP 手册的部分。

I suppose you could use a regular expression, which would match string and, then, end of string, coupled with the preg_replace() function.

Something like this should work just fine :

$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);

Notes :

  • string matches... well... string
  • and $ means end of string

For more informations, you can read the Pattern Syntax section of the PHP manual.

二货你真萌 2024-11-07 00:49:32

preg_replace 和此模式: /string\z/i

\z 表示字符串结尾

http://tr.php.net /preg_replace

preg_replace and this pattern : /string\z/i

\z means end of the string

http://tr.php.net/preg_replace

空城旧梦 2024-11-07 00:49:32

PHP 8 版本

function removePostfix(string $haystack, string $needle): string
{
    if (str_ends_with($haystack, $needle)) {
        return substr($haystack, 0, strlen($haystack) - strlen($needle));
    }


    return $haystack;
}

PHP 8 version

function removePostfix(string $haystack, string $needle): string
{
    if (str_ends_with($haystack, $needle)) {
        return substr($haystack, 0, strlen($haystack) - strlen($needle));
    }


    return $haystack;
}
‘画卷フ 2024-11-07 00:49:32

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

$string = "this is a test string";
$part = "string";
$string = implode( $part, array_slice( explode( $part, $string ), 0, -1 ) );
echo $string;
// OUTPUT: "this is a test "

IF you don't mind about performance AND the part of the string could be placed only at the end of string, THEN you can do this:

$string = "this is a test string";
$part = "string";
$string = implode( $part, array_slice( explode( $part, $string ), 0, -1 ) );
echo $string;
// OUTPUT: "this is a test "
岁月染过的梦 2024-11-07 00:49:32

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

if (!function_exists('str_ends_with')) {
    function str_ends_with($haystack, $suffix) {
        $length = strlen( $suffix );
        if( !$length ) {
            return true;
        }
        return substr( $haystack, -$length ) === $suffix;
    }
}

if (!function_exists('remove_suffix')) {
    function remove_suffix ($string, $suffix) {
        return str_ends_with($string, $suffix) ? substr($string, 0, strlen($string) - strlen($suffix)) : $string;
    }
}

@Skrol29's answer is the best, but here it is in function form and using the ternary operator:

if (!function_exists('str_ends_with')) {
    function str_ends_with($haystack, $suffix) {
        $length = strlen( $suffix );
        if( !$length ) {
            return true;
        }
        return substr( $haystack, -$length ) === $suffix;
    }
}

if (!function_exists('remove_suffix')) {
    function remove_suffix ($string, $suffix) {
        return str_ends_with($string, $suffix) ? substr($string, 0, strlen($string) - strlen($suffix)) : $string;
    }
}
水溶 2024-11-07 00:49:32

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

function right_trim(string $haystack, string $needle): string {
  if (str_ends_with($haystack, $needle)) {
    return substr($haystack, 0, -strlen($needle));
  }

  return $haystack;
}

With PHP 8, the code can be simpler.

function right_trim(string $haystack, string $needle): string {
  if (str_ends_with($haystack, $needle)) {
    return substr($haystack, 0, -strlen($needle));
  }

  return $haystack;
}
鹊巢 2024-11-07 00:49:32

有多种技术可用于将一根针线从另一根线的末端移除。 即使在多字节字符串上,下面的所有代码片段也能正确执行。某些函数具有细微的行为,我们将对此进行描述。

使用 preg_replace() 将无缝地允许替换干草堆字符串数组,这可能不需要手动实现循环。 preg_replace() 可以提供更多关于不区分大小写、全字匹配的工具,并可能在匹配之前清除不需要的空格或标点符号(如果需要)。将动态字符串值传递给 preg_ 函数时,建议对字符串中对正则表达式引擎具有特殊含义的字符进行转义。

代码: (PHPize 演示)

  1. 在图案中的针周围使用引号标记。这可以节省 preg_quote() 调用,但如果针包含 \E,则可能会被破坏。

    function rtrimNeedle1(string|array $haystack, string $needle): string|array {
        return preg_replace("/\\Q$needle\\E$/u", '', $haystack);
    }
    
  2. 使用preg_quote()将是转义针字符串中字符的最可靠方法。这可能是我专业使用的方法,因为它不需要考虑条件。由于模式分隔符是 #,因此 preg_quote() 不需要第二个参数 - 如果模式分隔符是正斜杠,则情况并非如此。

    function rtrimNeedle2(string|array $haystack, string $needle): string|array {
        return preg_replace('#' . preg_quote($needle) . '$#u', '', $haystack);
    }
    
  3. 有条件地使用 substr_replace() 删除不需要的后缀。

    function rtrimNeedle3(string $haystack, string $needle): string {
        return !str_ends_with($haystack, $needle)
            ? $干草堆
            : substr_replace($haystack, '', -strlen($needle));
    }
    
  4. 有条件地使用substr()来隔离针之前的前导字符。

    function rtrimNeedle4(string $haystack, string $needle): string {
        return !str_ends_with($haystack, $needle)
            ? $干草堆
            : substr($haystack, 0, -strlen($needle));
    }
    
  5. 有条件地使用 mb_substr()mb_strlen() 来隔离针前的前导字符。

    function rtrimNeedle5(string $haystack, string $needle): string {
        return !str_ends_with($haystack, $needle)
            ? $干草堆
            : mb_substr($haystack, 0, -mb_strlen($needle));
    }
    

请注意,非 mb_ 函数的行为与 mb_ 函数相同,因为 substr_replace()substr( ) 两者都对字节进行操作,而不是字符。由于mb_substr()的参数是字符,因此长度参数中必须使用mb_strlen()

There are multiple techniques which can be used to remove a needle string from the end of another string. All snippets below will perform correctly even on multibyte strings. Some functions have nuanced behaviors which will be described.

Using preg_replace() will seamlessly allow replacements on an array of haystack strings which may spare the need to manually implement a loop. preg_replace() can offer more tooling around case-insensitivity, whole-word matching, and potentially cleaning up unwanted spaces or punctuation before the match (if desired). When passing a dynamic string value to a preg_ function, it is recommended to escape characters in the string with special meaning to the regex engine.

Codes: (PHPize Demo)

  1. Use quoting markers around the needle in the pattern. This saves a preg_quote() call, but could be broken if the needle contains \E.

    function rtrimNeedle1(string|array $haystack, string $needle): string|array {
        return preg_replace("/\\Q$needle\\E$/u", '', $haystack);
    }
    
  2. Using preg_quote() will be the most reliable way to escape characters in the needle string. This is probably the method that I would use professionally because it doesn't need to faff around with conditions. Because the pattern delimiter is #, preg_quote() doesn't need a second parameter -- this is not true if the pattern delimiters are forward slashes.

    function rtrimNeedle2(string|array $haystack, string $needle): string|array {
        return preg_replace('#' . preg_quote($needle) . '$#u', '', $haystack);
    }
    
  3. Conditionally use substr_replace() to remove the unwanted suffix.

    function rtrimNeedle3(string $haystack, string $needle): string {
        return !str_ends_with($haystack, $needle)
            ? $haystack
            : substr_replace($haystack, '', -strlen($needle));
    }
    
  4. Conditionally use substr() to isolate the leading characters before the needle.

    function rtrimNeedle4(string $haystack, string $needle): string {
        return !str_ends_with($haystack, $needle)
            ? $haystack
            : substr($haystack, 0, -strlen($needle));
    }
    
  5. Conditionally use mb_substr() and mb_strlen() to isolate the leading characters before the needle.

    function rtrimNeedle5(string $haystack, string $needle): string {
        return !str_ends_with($haystack, $needle)
            ? $haystack
            : mb_substr($haystack, 0, -mb_strlen($needle));
    }
    

Notice that the non-mb_ functions behave identically to the mb_ function because the offset and length parameters of substr_replace() and substr() both operate on bytes, not characters. Because mb_substr()'s parameters are characters, mb_strlen() must be used in the length parameter.

漆黑的白昼 2024-11-07 00:49:31

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

$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);

You'll note the use of the $ character, which denotes the end of a string:

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

If the string is a user supplied variable, it is a good idea to run it through preg_quote first:

$remove = $_GET['remove']; // or whatever the case may be
$new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);
Saygoodbye 2024-11-07 00:49:31

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

以下内容适用于任何字符串,并遵循内置字符串函数使用的约定:

function right_trim(string $haystack, string $needle): string {
    $needle_length = strlen($needle);
    if (substr($haystack, -$needle_length) === $needle) {
        return substr($haystack, 0, -$needle_length);
    }
    return $haystack;
}

Using regexp may fails if the substring has special characters.

The following will work with any strings and follows conventions used by built-in string functions:

function right_trim(string $haystack, string $needle): string {
    $needle_length = strlen($needle);
    if (substr($haystack, -$needle_length) === $needle) {
        return substr($haystack, 0, -$needle_length);
    }
    return $haystack;
}
一个人练习一个人 2024-11-07 00:49:31

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

/**
 * @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;
}

I wrote these two function for left and right trim of a string:

/**
 * @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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文