Replace only at the end of the line

echo $string can give any text.

How to remove the word "blank" only if it is the last word $string ?

So, if we have a sentence like "Steve Blank is here" - nothing should be deleted, otherwise, if the sentence is "his name is Granblank" , then the word "Blank" should be deleted.

+6
source share
4 answers

You can easily do this with a regex. \b ensures that it is only deleted if it is a single word.

 $str = preg_replace('/\bblank$/', '', $str); 
+16
source

As a Teez answer option:

 /** * A slightly more readable, non-regex solution. */ function remove_if_trailing($haystack, $needle) { // The length of the needle as a negative number is where it would appear in the haystack $needle_position = strlen($needle) * -1; // If the last N letters match $needle if (substr($haystack, $needle_position) == $needle) { // Then remove the last N letters from the string $haystack = substr($haystack, 0, $needle_position); } return $haystack; } echo remove_if_trailing("Steve Blank is here", 'blank'); // OUTPUTS: Steve blank is here echo remove_if_trailing("his name is Granblank", 'blank'); // OUTPUTS: his name is Gran 
+4
source

Try the following code:

 $str = trim($str); $strlength = strlen($str); if (strcasecmp(substr($str, ($strlength-5), $strlength), 'blank') == 0) echo $str = substr($str, 0, ($strlength-5)) 

Do not use preg_match unless required. PHP itself recommends using string functions over regular expression functions when matching is simple. From the preg_matc h. Man page.

+1
source

ThiefMaster is quite correct. A technique that is not related to the regular expression $ end of line character will be to use rtrim .

 $trimmed = rtrim($str, "blank"); var_dump($trimmed); 

^ This is if you want to delete the last characters of a string. If you want to delete the last word:

 $trimmed = rtrim($str, "\sblank"); var_dump($trimmed); 
-3
source

Source: https://habr.com/ru/post/1389567/


All Articles