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.
Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.
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.
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.
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.
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);
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With