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 :
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);
You can use rtrim().
php > echo rtrim('this is a test string', 'string');
this is a test
This will work only in some cases, as 'string'
is just a characters mask and char order will not be respected.
preg_replace and this pattern : /string\z/i
\z means end of the string
http://tr.php.net/preg_replace
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 "
Using regexp may fails if the substring has special characters.
The following will work with any strings:
$substring = 'string';
$str = "this string is a test string";
if (substr($str,-strlen($substring))===$substring) $str = substr($str, 0, strlen($str)-strlen($substring));
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
$
means end of stringFor more informations, you can read the Pattern Syntax section of the PHP manual.