Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace all matches unless the match is at the end of the string

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?

like image 852
Alex Naspo Avatar asked Dec 21 '22 10:12

Alex Naspo


1 Answers

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";
like image 114
Bart Kiers Avatar answered Dec 28 '22 07:12

Bart Kiers