What I have is "text - something else“, now with the below code I can convert it to "text-something-else", but I’m unhappy with the extra replace.
Is there anyway to merge each into one line?
PHP:
$url = strtolower(str_replace(" ", "-", splitstring($item->item)));
$url = str_replace("---", "-", $url);
JS:
title = title.toLowerCase().replace(/ /g, '-');
title = title.replace(/---/g, '-');
The latter replaces prevent this: "text---something-else", so they’re needed.
Use the power of regular expressions:
or:
The above will obviously replace any number of hyphens or spaces with a singular hyphen, which is slightly different from your previous logic. If you wish to take into account any other characters you can easily do the following:
The above will match any white space, hyphen or underscore.
As a word of warning when using a hyphen in your regular expression you should make sure it is at the end of the
[bracketed]group i.e.[abc-]or you will need to escape it using a backslash, like[a\-bc]. This is because regular expression syntax allows you to match ranges such as0-9which will not be what you intend in this situation.