When I replace spaces, dots and commas of a string, it sometimes happens that I get double hyphens.
For example turns check out the 1. place
into check-out-the-1--place
How can I avoid that? I want it to be check-out-the-1-place
- so that there only is one hyphen between each word. Here is my code:
str_replace([' ', ',', '.','?'], '-', strtolower($pathname));
Right now, I know why it returns the double-hyphens, but I don't know how to work around that.
Can someone help me out?
How can I avoid that? I want it to be check-out-the-1-place - so that there only is one hyphen between each word. Here is my code:
Whilst Mohammad's answer is nearly there, here is a more fully working PCRE regex method and explanation as to how it works, so you can use it as you need:
$str = trim(strtolower($pathname));
$newStr = preg_replace('/[\s.,-]+/', '-', $str);
How this works:
[\s.,-]+
+
Quantifier Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)\s
matches any whitespace character (equal to [\t\f\v
]).,-
matches a single character in the list .,-
(case sensitive)-
must come at the end of the []
set.Results:
This: check out the 1. place
Becomes:
check-out-the-1-place
And
This: check out the - 1. place
Becomes
check-out-the-1-place
I would go further and assuming you are using this for a URL slug (a what?!); strip out all non-alphanumeric characters from the string and replace with a single -
as per typical website slugs.
$newStr = preg_replace('/[^a-z0-9]+/i', '-', $str);
How this works:
^
) present in the list below [a-z0-9]+
+
Quantifier Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)a-z
a single character in the range between a (index 97) and z (index 122) (case sensitive)0-9
a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)i
at the end indicates the judgements are case In-sensitive.Example:
check out - the no.! 1. Place
Becomes:
check-out-the-1-Place
You can use preg_replace()
instead and user regex to selecting multiple specific character.
$newStr = preg_replace("/[\s.,]+/", "-", $str)
Check result in demo