Skip to content
Fix Code Error

Remove all special characters from a string

March 13, 2021 by Code Error
Posted By: Anonymous

I am facing an issue with URLs, I want to be able to convert titles that could contain anything and have them stripped of all special characters so they only have letters and numbers and of course I would like to replace spaces with hyphens.

How would this be done? I’ve heard a lot about regular expressions (regex) being used…

Solution

This should do what you’re looking for:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"[email protected]£de^&$f g');

Will output: abcdef-g

Edit:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
Answered By: Anonymous

Related Articles

  • PHP: How to remove all non printable characters in a string?
  • Reference - What does this regex mean?
  • easiest way to extract Oracle form xml format data
  • Issue with iron-ajax request
  • Is it possible to apply CSS to half of a character?
  • What are the undocumented features and limitations of the…
  • Fastest way to iterate over all the chars in a String
  • Understanding constraints in agrep fuzzy matching in R
  • How do i arrange images inside a div?
  • Best way to replace multiple characters in a string?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Next Post:

CSS background image to fit width, height should auto-scale in proportion

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error