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:
$string = "How can I fix this?";
$patterns = array('/[^0-9a-z.]+/i', '/[^0-9a-z.]+(?=$)/i');
$replacements = array('-', '');
echo preg_replace($patterns, $replacements, $string) . "\n";
which prints:
How-can-I-fix-this
Which is really nothing more than two successive replacements:
$string = "How can I fix this?";
echo preg_replace('/[^0-9a-z.]+/', '-', preg_replace('/[^0-9a-z.]+$/', '', $string)) . "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With