Home > Article > Backend Development > How to Strip Non-Alphanumeric Characters and Replace Spaces with Hyphens Using Regular Expressions?
Stripping Non-Alphanumeric Characters and Replacing Spaces with Hyphens
Problem: Users face challenges when converting titles into URLs that only contain letters, numbers, and hyphens. They seek a way to strip special characters and replace spaces with hyphens.
Solution: Regular Expressions (Regex)
Regular expressions are a powerful tool for pattern matching and string manipulation. They can be used to achieve the desired transformations.
Code:
<code class="php">function clean($string) { // Replace spaces with hyphens $string = str_replace(' ', '-', $string); // Remove non-alphanumeric characters and hyphens $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Replace multiple hyphens with a single one $string = preg_replace('/-+/', '-', $string); return $string; }</code>
Usage:
<code class="php">echo clean('a|"bc!@£de^&$f g');</code>
Output:
abcdef-g
Additional Modification:
To prevent multiple hyphens from appearing consecutively, replace the last line of the clean function with:
<code class="php">return preg_replace('/-+/', '-', $string);</code>
The above is the detailed content of How to Strip Non-Alphanumeric Characters and Replace Spaces with Hyphens Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!