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

我需要删除一个字符串的子字符串,但只有当它在字符串的最后。

例如,删除以下字符串末尾的“ 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"

知道是什么吗? 可能是某种怀孕替代品,但是怎么做到的呢?

66335 次浏览

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

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.

preg_replace and this pattern : /string\z/i

\z means end of the string

http://tr.php.net/preg_replace

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;
}

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;
}

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 "

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

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;
}