Use PHP to remove certain characters or words from a string

The default PHP function str_replace(); is a useful tool if we want to remove certain characters, symbols or words from a string. Below I show you how to work with it.

How do I remove specific characters from a string?

The following wrapper function shows how we can use PHP to remove specific characters from a value or text. We simply pass the text or value to the function. This is done as follows: clear_string_from_characters("A [text] with $ characters");

  • Start value: A [text] with $ characters.
  • End value: A text with characters.

In the above function we can see the array(); contains characters defined that should not be included in the output. With the variable $replace = ''; We have decided that the previously defined characters are replaced by an empty value and will be completely removed. Therefore, the characters “[“, “]” and “$” are removed from the start value.

How do I remove words from a string?

The next example shows how to replace the number “6” with an empty value and the word “old” with “young”.

  • Start value: I’m 68 years old.
  • End value: I’m 8 years young.

Of course, if you do not need a wrapper function, you can just use the default PHP function str_replace(); use, as the following example shows:

In the above example code by using PHP we have replaced the word “Hello” by “Howdy”.