Regular Expression Sanitize (PHP)

  • Added:
  • |
  • In: Basic PHP

I would like to sanitize a string in to a URL so this is what I basically need.

  1. Everything must be removed except alphanumeric characters and spaces and dashed.
  2. Spaces should be converter into dashes.


This, is the URL!

must return

This Question Has 5 Answeres | Orginal Question | Atif Mohammed Ameenuddin

All previous asnwers deal with url, but in case some one will need to sanitize string for login (e.g.) and keep it as text, here is you go:

function sanitizeText($str) {
    $withSpecCharacters = htmlspecialchars($str);
    $splitted_str = str_split($str);
    $result = '';
    foreach ($splitted_str as $letter){
        if (strpos($withSpecCharacters, $letter) !== false) {
            $result .= $letter;
    return $result;

echo sanitizeText('??????????? ajvnsakjvnHB "&nvsp;\n" <script>alert()</script>');
//??????????? ajvnsakjvnHB &nvsp;\n scriptalert()/script
//No injections possible, all info at max keeped

Try This

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.


echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

source :

This will do it in a Unix shell (I just tried it on my MacOS):

$ tr -cs A-Za-z '-' < infile.txt > outfile.txt

I got the idea from a blog post on More Shell, Less Egg

First strip unwanted characters

$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

Then changes spaces for unserscores

$url = preg_replace('/\s/', '-', $new_string);

Finally encode it ready for use

$new_url = urlencode($url);
function slug($z){
    $z = strtolower($z);
    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
    $z = str_replace(' ', '-', $z);
    return trim($z, '-');

I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.
Connect Social With PHPAns