Run
Run

Reputation: 57176

Remove any letter which is not an alphabet or a number?

I use preg_match to allow alphabets and numbers in the input,

if(!preg_match('/^[a-zA-Z0-9]+$/', $file_rename))
{
$error = true;
echo '<error elementid="file_rename" message="FILE - please use alphabets and numbers only" />';
}

What if I want to remove any letter which is not an alphabet or a number?

For instance,

test_1

to

test 1

or,

test&2

to

test 2

Upvotes: 0

Views: 1266

Answers (2)

Phil
Phil

Reputation: 164752

Initially, I'd go with this (unicode safe)

$newString = preg_replace('/[^\p{L}\p{N}]/u', ' ', $oldString);

If you want to leave existing, multiple spaces alone...

$newString = preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $oldString);

If you want to compact consecutive non-alpha-numeric characters into a single space, change it to

$newString = preg_replace('/[^\p{L}\p{N}]+/u', ' ', $oldString);
// note the + sign

Upvotes: 3

user895378
user895378

Reputation:

PHP preg_replacedocs is what you're looking for:

$str = preg_replace('/[^a-z0-9]/i', ' ', $str);

Note the i modifier at the end of the regex -- it makes the search case-insensitive. If you don't mind underscores, you can alternatively just do:

$str = preg_replace('/[^\w]/', ' ', $str);

Upvotes: 4

Related Questions