3

I convert any special characters to dashes in my string except for alphanumerics using this:

return preg_replace("![^a-z0-9]+!i", "-", $str);

However, in some case I have this strings:

$str = "Hello there chubby!";

which will result to:

Hello-there-chubby-

The dash on the end of word is what makes me think of a solution on how to remove that.

fishcracker
  • 2,221
  • 5
  • 22
  • 25

2 Answers2

7
return trim(preg_replace("![^a-z0-9]+!i", "-", $str), '-');

will strip leading and trailing dashes.

cryptic ツ
  • 14,925
  • 9
  • 50
  • 79
2

You can try rtrim("Hello-there-chubby-", "-");.

or

preg_replace("#[^a-z0-9]+$#ims", "", "Hello-there-chubby-");

for removing the last special character.

Sandeep Varma
  • 313
  • 2
  • 10