PHP cleaning strings with “preg_replace()” function and more resources for REGEX

Cleaning strings by removing anything that is not a letter or number can be very useful, like building clean URLs based on customer data.

This will replace anything that isn’t a letter, number or space. Then, you can further clean the spaces by replacing with dashes (“-“) for better URL readability.


$stringToClean = preg_replace("/[^a-zA-Z 0-9]+/", "", $stringToClean);

Note that “preg_replace” uses the REGEX patterns and matching rules which is also used in .htaccess files. If sometimes you struggle with getting REGEX right, visit this excellent REGEX Cheatsheet: http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

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