Jump to content

[SOLVED] how to strip illegal chars by regex


amb99

Recommended Posts

Hi,

 

I've read quite a bit and from my understanding I can check if the string is alphanumeric (and _-) by doing:

 

if (preg_match('/^[a-zA-Z0-9_.]+$/', $string)) {
echo "invalid chars.";
}

 

But, how can I return the string with every illegal character stripped out? (with the exception of _-)

 

Thank you for any help.

That seems to be correct.. however I've tried doing:

 

$pattern = '/^[A-Za-z0-9_.]+$/';
$replacement = '';
$out = preg_replace($pattern, $replacement, $string);
echo "out: $out";

 

The result $out isn't getting stripped of any illegal chars though. I thought it mightve been related to $ in /^[A-Za-z0-9_.]+$/', so as a test I changed it to /^[A-Za-z0-9_.]/', but still no luck.  :(

Here is a non-regex version:


<?php

$string = "gsjdtb7l,-'%&!";

echo str_replace(array_values(str_replace(array_merge(range(a,z),range(A,Z),range(0,9),array('-','.')),'',str_split($string))),'',$string);

// prints: gsjdtb7l-

?>

 

EDIT* Requires php5 though due to str_split()

Try this...

 

<?php
$pattern = '/[^\w\.]/i';
$replacement = '';
$out = preg_replace($pattern, $replacement, $string);
echo "out: $out";
?>

 

This says replace anything that's not a word character (letters a-z, numbers 0-9, and the underscore) or a period (.) with nothing.

 

Regards

Huggie

alpine: I'm using 4.X so I was unfortunately unable to test that method.

HuggieBear: That worked wonderfully!

 

No problem, your code was fine, it was missing one important character though.  The circumflex (^) at the start of the character class that negates it.  Basically says, match anything that's NOT one of the following characters.

 

I just used the word meta character (\w) to simplify what you'd written.

 

Regards

Huggie

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.