[英]Using preg_replace()?
I'm trying to understand the function preg_replace(), but it looks rather cryptic to me. 我正在尝试理解preg_replace()函数,但它对我来说看起来很神秘。 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: "".
到目前为止,我知道我需要允许数字0-9,但删除任何不是数字的内容并将其替换为:“”。
Instead of escaping every character I need to, is there some way to simply not allow any other character than the numbers 0-9? 而不是逃避我需要的每一个角色,是否有一些方法可以简单地不允许任何其他字符而不是数字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. 模式
[0-9]
将匹配所有数字。 Placing a caret ( ^
) at the beginning of the set matches everything that isn't in the set: [^0-9]
放置一个插入符号(
^
在设定的开始)相匹配的一切, 是不是在集: [^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: preg_replace()
比你想象的容易:
$p = "/[A-Z a-z]/";
$r = "";
$s = "12345t7890";
echo preg_replace($p, $r, $s);
Will output "123457890" - note no '6' 输出“123457890” - 注意没有'6'
is_numeric();
isn't resolve your problem ? 是不是解决了你的问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.