Regular Expression Find And Replace With PHP
Today, I wanted to show you a good one line to find and replace characters not wanted in a string or filename within PHP.
The below regular expression only accepts numbers and letters. It will replace the spaces and periods in this example string replace.
To take it a bit further, look at the next few lines. I started to see if there were characters not wanted in the string that were side by side, we would get the replace characters next to each other. To remedy this, we can have the str_replace function that looks for double and triple replace characters beside one another, and replace it with the single replace character (lines 1 & 2).
Then we need to trim the replace character from the beginning and end of string with this line.
That will do it! Hope this helped.