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,401
  • 5
  • 23
  • 28

2 Answers2

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

will strip leading and trailing dashes.

kittycat
  • 14,983
  • 9
  • 55
  • 80
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
  • 322
  • 2
  • 11