1

I need to change some of the strings to SEO-friendly slugs. I think I'm pretty close with this:

str_replace(array(" ", "&", "(", ")", ".", ",", " - ", "'"), array("-", ""), strtolower($str))

However there are couple of cases that I still have issues with. It's when a string has a dash or & as in:

I & GN Hospital and Nurses' Quarters

produces i--gn-hospital-and-nurses-quarters instead of desired i-gn-hospital-and-nurses-quarters

Also I would like to strip anything enclosed in () before creating a slug. For example:

Mary Kate Hunter (November 8, 1866 - April 15, 1945)

should become mary-kate-hunter

I think I'll need another str_replace first to remove it, before creating slug, and possibly use some sort of regex. Or is there a better way?

anubhava
  • 761,203
  • 64
  • 569
  • 643
santa
  • 12,234
  • 49
  • 155
  • 255
  • This question has been already answered [PHP function to create slug ](https://stackoverflow.com/questions/2955251/php-function-to-make-slug-url-string) – Gazmend Sahiti Oct 30 '20 at 16:48

1 Answers1

1

You may use this code with preg_replace instead of str_replace to do replacements using a regex.

$s = 'I & GN Hospital and Nurses' Quarters';
echo preg_replace("/[\h&(),'-]+/", '-', preg_replace('/\h*\([^)]*\)/', '', $s));
//=> I-GN-Hospital-and-Nurses-Quarters

$p = 'Mary Kate Hunter (November 8, 1866 - April 15, 1945)';
echo preg_replace("/[\h&(),'-]+/", '-', preg_replace('/\h*\([^)]*\)/', '', $p));
//=> Mary-Kate-Hunter

Here:

  • preg_replace('/\h*\([^)]*\)/', '', $s): Strips out (...) text from input
  • preg_replace("/[\h&(),'-]+/", '-', $str): Replaces all chosen characters with -
anubhava
  • 761,203
  • 64
  • 569
  • 643