简体   繁体   中英

Using preg_replace()?

I'm trying to understand the function preg_replace(), but it looks rather cryptic to me. From looking at the documentation on the function here . I understand that it consists of three things - the subject, the pattern for matching, and what to replace it with.

I'm currently trying to 'sanitize' numerical input by replacing anything that isn't a number. So far I know I would need to allow the numbers 0-9, but remove anything that isn't a number and replace it with: "".

Instead of escaping every character I need to, is there some way to simply not allow any other character than the numbers 0-9? Also if anyone could shed light on how the 'pattern for matching' part works...

If you want to sanitize a string to replace anything that isn't a number, you would write a regular expression that matches characters not in list.

The pattern [0-9] would match all numerals. Placing a caret ( ^ ) at the beginning of the set matches everything that isn't in the set: [^0-9]

$result = preg_replace('/[^0-9]/', '', $input);

Note that this will also filter out periods/decimal points and other mathematical marks. You could include periods/decimal points (allowing floats) by making the period allowed:

$result = preg_replace('/[^0-9.]/', '', $input);

Note that the period ( . ) is the wildcard character in regular expressions. It doesn't need to be escaped in a bracket expression, but it would elsewhere in the pattern.

preg_replace() is easier than you think:

$p = "/[A-Z a-z]/";
$r = "";
$s = "12345t7890";

echo preg_replace($p, $r, $s);

Will output "123457890" - note no '6'

is_numeric(); isn't resolve your problem ?

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