I am currently using what appears to be a horribly complex and unnecessary solution to form a required string.
The string could have any punctuation and will include slashes.
As an example, this string:
Test Ripple, it\'s a comic book one!
Using my current method:
str_replace(" ", "-", trim(preg_replace('/[^a-z0-9]+/i', ' ', str_replace("'", "", stripslashes($string)))))
Returns the correct result:
Test-Ripple-its-a-comic-book-one
Here is a breakdown of what my current (poor) solution is doing in order to achieve the desired output:-
- Strip all slashes from the string
- remove any apostrophes with str_replace
- remove any remaining punctuation using preg_replace and replace it with whitespace
- Trim off any extra whitespace from the beginning/end of string which may have been caused by punctuation.
- Replace all whitespace with ‘-‘
But there must be a better and more efficient way. Can anyone help?
Personally it looks fine to me however I would make one small change.
Change
to the following