Search code examples
phpphp-5.3slug

PHP Slug Generation Function Giving Improper Output


I am using below code to get a proper slug that I am sending from an ajax call.

$slug = strtolower(trim(preg_replace('/[^A-Za-z]+/', '-', $_POST['slug'])));

But, what's happening is. If from an ajax request I am getting any slug-like

slug: top-5-ways--to-avoid-list-

I want to trim unwanted - hyphens and any numeric values from the slug and want the below slug

slug: top-ways-to-avoid-list

I am not able to understand that what is wrong with the code.


Solution

  • slugify your string this way, it'll remove unwanted characters including -.

    trim() takes as 2nd parameter all characters that you want to be stripped. So have a look on the commented line THIS WILL FIX YOUR EXISTING PROBLEM

    <?php
    function slugify($string, $delimiter = '-'){
      $clean = preg_replace("/[^a-zA-Z\/_|+ -]/", '', $string); 
      $clean = strtolower($clean);
      $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
      $clean = trim($clean, $delimiter); // THIS WILL FIX YOUR EXISTING PROBLEM
      return $clean;
    }
    
    echo slugify('-Top ways-to avoid list-');
    echo PHP_EOL;
    echo slugify('top 5 ways to get in top');
    ?>
    

    Output:

    top-ways-to-avoid-list 
    top-ways-to-get-in-top
    

    DEMO: https://3v4l.org/ljtlZ

    OR with your existing code trimming multiple characters - or spaces

    <?php
    echo strtolower(trim(preg_replace('/[^A-Za-z]+/', '-', '-Top ways-to avoid list-'),'- '));
    echo PHP_EOL;
    echo strtolower(trim(preg_replace('/[^A-Za-z]+/', '-', 'top 5 ways to get in top'),'- '));
    ?>
    

    DEMO: https://3v4l.org/aBtHI