I’m using php to clean out names to be used in a url slug:, where $title might look like this: “This is the Title” or “This is the Title & Subtitle”
Those above examples I want to change to “this-is-the-title” and “this-is-the-title-subtitle”, respectively. So, I made this code….
<?php
$input1 = str_replace(" ","-",strtolower($title));
$output1 = preg_replace('/[^A-Za-z0-9-]/', '', $input1);
$output2 = str_replace("--","-",$output1);
echo $output2;
?>
It’s working great, cleaning out all the non-alpha numeric, replacing spaces with dashes and making everything lower case.
However, in some instances, it’s returning the double dash (“Title & More” turns to (“title–more”). It should be “title-more”. I know why the double dash is there, but I can’t seem to clean it out.
I put in the line of code for $output2, but it doesn’t seem to be working for some reason. After lots of trial and error, I’m at a loss.
Thanks…
You can solve the same in a single regex:
The only change I made was the trailing
+in the regex, meaning “1 or more occurances of the previous group”. Now every group of special characters is replaced with a single dash – no matter how long the group is.Just for answering the actual question, though: You would need to reduce duplicate dashes in a loop in your case:
(I would seriously consider renaming the variables, though)