Remove undesired characters with trim_all() – PHP

This function was inspired from PHP’s built-in function trim() that removes undesired characters from the start and end of a string, and in case no such characters are provided as second argument to the function, it removes white-space characters from both ends of the string.

So, what does trim_all() do?

trim_all() was intended to remove all instances of white-spaces from both ends of the string, as well as remove duplicate white-space characters inside the string. But, later on, I made it a general purpose function to do a little more than just white-space trimming and cleaning, and made it to accept custom characters to replace and to replace with in the string. With this function, you can:

  • normalize white-spaces, so that all multiple \r, \n, \t, \r\n, \0, 0x0b, 0x20 and all control characters can be replaced with a single space, and also trimed from both ends of the string;
  • remove all undesired characters;
  • remove duplicates of any character;
  • replace multiple occurrences of characters with a character or string.

This function can be helpful when you want to remove unwanted characters from users’ input. Here is how to use it.

Example Use