简体   繁体   中英

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

PHP preg_replace docs 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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM