Search code examples
preg-replaceslugremoving-whitespace

How to remove whitespace + hiphen + whitespace to only hiphen in url slug with preg_replace


I am using this function. Everything works fine but When i enter item title like : "Example - A digital product" it shows me in url slug example---a-digital-product..Here after word example there are 3 hiphen continuous. Please help to resolve it.

public function item_slug($string){
        $slug=preg_replace(array('/[^A-Za-z0-9 -]+/','/[ -]+/'), array('',''),$string);
       return $slug;
}

Solution

  • You could use a hyphen in the second replacement to replace 1 or more occurrences of a space or hyphen you match with [ -]+ with a single hyphen.

    Example code:

    function item_slug($string){
        return preg_replace(array('/[^A-Za-z0-9 -]+/','/[ -]+/'), array('','-'),$string);
    }
    
    $strings = [
        "example---a-digital-product..",
        "Example - A digital product"
    ];
    
    foreach ($strings as $str) {
        echo item_slug($str) . PHP_EOL;
    }
    

    Output

    example-a-digital-product
    Example-A-digital-product
    

    Php demo