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.

Link to comment
Share on other sites

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.  :(

Link to comment
Share on other sites

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()

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.