-1

I am trying to convert:

" Long Grain IRRI-6 White Rice "

to

" long_grain_irri_6_white_rice "

but it's returning this

" long_grain_irri-6_white_rice "

Here is the code:

public function phpslug($string){
    $slug = preg_replace('/[^a-z0-9-]+/', '_', strtolower($string));
    return $slug;
}

I want it to remove not only space between letters, I need it to remove also "-" this, so it can replace with "_".

How do I solve this problem?

Zain Farooq
  • 2,956
  • 3
  • 20
  • 42
Zain Shabir
  • 395
  • 6
  • 18

1 Answers1

1

You might remove - from your RegEx pattern:

function phpslug($string)
{
    $slug = preg_replace('/[^a-z0-9]+/', '_', strtolower(trim($string)));
    return $slug;
}

var_dump(phpslug("  Long Grain IRRI-6 White Rice  "));

or you might simplify your RegEx pattern:

function phpslug($string)
{
    $slug = preg_replace('/[-\s]+/', '_', strtolower(trim($string)));
    return $slug;
}

var_dump(phpslug("  Long Grain IRRI-6 White Rice  "));

Output:

 string(28) "long_grain_irri_6_white_rice"
Emma
  • 27,428
  • 11
  • 44
  • 69
  • you have edited with new answer, this one not working, but the old answer to remove "-" from RegEx patern, that worked properly Thanks for that – Zain Shabir Apr 22 '19 at 06:00