Converting Strings to Slugs with Single-Hyphen Delimiters
In the realm of web development, it's often necessary to convert strings into slugs for URL optimization. Slugs are strings with alphanumeric characters, spaces, and hyphens only, used to create readable and search engine-friendly URLs.
Problem:
Suppose we have a string that we need to sanitize into a URL. Our requirements are:
For instance, the string "This, is the URL!" should become "this-is-the-url".
Solution:
To address this problem, we can utilize a custom function like the one below:
<code class="php">function slug($z) { $z = strtolower($z); $z = preg_replace('/[^a-z0-9 -]+/', '', $z); $z = str_replace(' ', '-', $z); return trim($z, '-'); }</code>
Here's how this function works:
The above is the detailed content of How to Create Single-Hyphen Delimited Slugs from Strings for URL Optimization?. For more information, please follow other related articles on the PHP Chinese website!