Search code examples
phpregexslug

accept only alphabets and numbers. Replace others by single '-'. PHP


In my code, I have a function for remove all non-alphabetic and non-numeric characters with a '-'. But the problem is my regex just removing the special character what evre it is with '-'. So if the input is

((hai..)how   are you?)

will change as

--hai---how---are-you--

I need to combine all adjacent '-' as one.And remove the starting and ending special characters. that is the above result become

 hai-how-are-you

my function is

function to_slug($string)
{
    $string = trim($string);
    return $string1 = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));
}

and i got a regex code for combine the '-'.

trim(preg_replace('/-+/', '-', $str), '-')

But i don't know how to combine this. Please help.. Thank you in advance


Solution

  • Try this:

    function toSlug($string){
        $string = trim($string);
        return strtolower(trim(preg_replace('/([^0-9a-z]+)/i', '-', $string), '-'));
    }