0

What I am looking for by using preg_replace is replacing ". or ' or space" from string with "-".

Like replacing "Some St. Street O' Corner" into "some-st-street-o-corner".

How i am achieving this is by using below way.

$string = "Some St. Street O' Corner";

$new_string = preg_replace('/\\.|\\'/', '', $string);

$final_string = str_replace(' ', '-', $new_string);

Is there any better way to get it done by just using preg_replace?

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • See https://3v4l.org/lMdJT – Wiktor Stribiżew May 09 '22 at 20:37
  • @Wiktor Thanks for quick solution. It's working great. But if . or ' at the end, it's adding -. which is quite obvious but can that be stopped from adding in case string ends with . or ' https://3v4l.org/j2P5t I am just not good in regex thing :( – Amit Sharma May 09 '22 at 20:51
  • https://3v4l.org/SvelS – Wiktor Stribiżew May 09 '22 at 20:58
  • Great. https://3v4l.org/SvelS it works the way I wanted. Thanks for taking your time to solve my concerned @Wiktor. Cheers!! – Amit Sharma May 09 '22 at 21:05
  • This question already has answers here: https://stackoverflow.com/questions/7995106/how-to-replace-two-different-characters-with-one-character-using-preg-replace anyway, this link is not solution of what i asked for. – Amit Sharma May 09 '22 at 21:14
  • @AmitSharma: Only use `preg_replace` is false good idea to slug a string. If you want something appropriate to do that in one shot, use the intl transliterator. See the new [duplicate link](https://stackoverflow.com/questions/2955251/php-function-to-make-slug-url-string). – Casimir et Hippolyte May 10 '22 at 19:22

0 Answers0