views:

33

answers:

2

Hey Guys,

I'm looking for a php preg replace to null/empty string if string contains any non alphanumeric characters or spaces

e.g. Strings

$string = "This string is ok";
$string = "Thi$ string is NOT ok, and should be emptied"

When I say emptied/nulled I mean it will make the string "".

So basically anything a-z A-Z 0-9 or space is ok

Any ideas?

+1  A: 
if(preg_match('~[^a-z0-9 ]~i', $str))
      $str = '';
stereofrog
+1  A: 

You can use this pattern (note the possessive quantifier) to match "invalid" strings:

^[a-zA-Z0-9 ]*+.+$

Here's a snippet:

<?php

$test = array(
  "This string is ok",
  "Thi$ string is NOT ok, and should be emptied",
  "No way!!!",
  "YES YES YES"
);

foreach ($test as $str) {
  echo preg_replace('/^[a-zA-Z0-9 ]*+.+$/', '<censored!>', $str)."\n";
}

?>

The above prints (as seen on ideone.com):

This string is ok
<censored!>
<censored!>
YES YES YES

It works by using possessive repetition (i.e. no backtracking) to match as many valid characters as possible with [a-zA-Z0-9 ]*+. If there's anything left after this, i.e. .+ matches, then we must have gotten stuck at an invalid character, so the whole string gets matched (and thus replaced). Otherwise the string remains untouched.

The string '<censored!>' is used as replacement here for clarity; you can use the empty string '' if that's what you need.

References

polygenelubricants