Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only at the end of the string

echo $string can give any text.

How do I remove word "blank", only if it is the last word of the $string?

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

like image 726
Jasper Avatar asked Jan 05 '12 23:01

Jasper


People also ask

How do I change the end of a string?

Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.

How do you change the end of a string in Python?

In Python, the . replace() method and the re. sub() function are often used to clean up text by removing strings or substrings or replacing them.

How do you replace a part of a string with another string?

Replace part of a string with another string in C++ There is a function called string. replace(). This replace function replaces only the first occurrence of the match.

How do you replace values in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


2 Answers

You can easily do it using a regex. The \b ensures it's only removed if it's a separate word.

$str = preg_replace('/\bblank$/', '', $str);
like image 187
ThiefMaster Avatar answered Sep 18 '22 02:09

ThiefMaster


As a variation on Teez's answer:

/**
 * 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
like image 35
Fleep Avatar answered Sep 21 '22 02:09

Fleep