Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a part of a string, but only when it is at the end of the string

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

like image 745
Dylan Avatar asked Apr 06 '11 21:04

Dylan


2 Answers

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); 
like image 186
Tim Cooper Avatar answered Oct 13 '22 19:10

Tim Cooper


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)); 
like image 42
Skrol29 Avatar answered Oct 13 '22 18:10

Skrol29