I am currently using this regex to replace all non alpha numeric characters from a string and replace them with a dash
$newString = preg_replace("/[^a-z0-9.]+/i", "-", $string);
This works fine for the following string.
$string = "this will work fine";
$newString = "this-will-work-fine";
But if the string has a non alpha numeric as the final character it will match and replace that, as one would suspect.
$string = "How can I fix this?";
$newString = "How-can-I-fix-this-";
How can I improve this regex to have the following output?
$newString = "How-can-I-fix-this";
The regex should work in both cases. I know I can just trim down the string with a separate function, but ideally I would like to use one regex. It this possible?
Since you’re using PHP, you can define multiple patterns & replacements in one go. Here’s a quick demo:
which prints:
Which is really nothing more than two successive replacements: