Home > Backend Development > PHP Tutorial > How to Generate URL-Friendly Slugs with Hyphens Only in PHP?

How to Generate URL-Friendly Slugs with Hyphens Only in PHP?

DDD
Release: 2024-10-26 17:59:30
Original
578 people have browsed it

How to Generate URL-Friendly Slugs with Hyphens Only in PHP?

URL-Friendly Slug Generation with Hyphens Only

String sanitization is essential for creating URL-friendly strings, known as slugs. These slugs facilitate easy navigation and search engine optimization. To convert a string into a slug with single-hyphen delimiters, removing all non-alphanumeric characters and spaces, consider the following approach:

1. Remove Non-Essential Characters:
Using a regular expression, we can identify all non-alphanumeric characters and spaces. These are removed to ensure a clean slug.

2. Replace Spaces with Dashes:
Spaces within the string should be replaced with hyphens (-) to create a delimiter between words. This ensures readability in the slug.

Example:

Consider the string:

This, is the URL!
Copy after login

Applying the above algorithm, we get the slug:

this-is-the-url
Copy after login

Implementation in PHP:

Here's a PHP function that implements the slug generation algorithm:

<code class="php">function slug($z){
    $z = strtolower($z);
    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
    $z = str_replace(' ', '-', $z);
    return trim($z, '-');
}</code>
Copy after login

Usage:

To use this function, simply provide the input string as an argument and assign the returned value to a variable.

Example Usage:

<code class="php">$input = 'This, is the URL!';
$slug = slug($input);

echo $slug; // Output: this-is-the-url</code>
Copy after login

The above is the detailed content of How to Generate URL-Friendly Slugs with Hyphens Only in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template