Search code examples
phpstringtrim

PHP trim entire words


How to trim entire words from php string

like I dont want "foo", "bar", "mouse" words on left and "killed" on the end of string.

So "fo awesome illed" would not be trimmed

But "foo awesome killed" => " awesome "

"killed awesome foo" not trimmed (killed trimmed from right, rest from left)

When I'm using ltrim($str, "foo"); it will trim any letter from "foo" - "f" or "o"


Solution

  • Use preg_replace() to replace the strings with an empty string.

    $str = preg_replace('/^(foo|bar|mouse)|killed$/', '', $str);
    

    Go to regular-expressions.info to learn more about regexp.