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