我有一个包含2个信息的字符串(1.布尔值/2.某些东西(可以是数字、字母、特殊字符,也可以是任何长度))。
2是用户输入。
示例:
(part 1)"true".(part 2)"321654987" => "true321654987"
也可能是
"false321654987" or "trueweiufv2345fewv"
我需要的是一种解析字符串的方法,首先检查1是否是true
(如果它为false,则什么都不做),如果它是true
,我需要检查后面的部分是否是大于0的正数(必须接受任何大于0的数字,即使是十进制,但不是二进制或十六进制(好吧…可能是10,但它意味着10而不是2))。
以下是我尝试过的:
//This part is'nt important it work as it should....
if(isset($_POST['validate']) && $_POST['validate'] == "divSystemePositionnement")
{
$array = json_decode($_POST['array'], true);
foreach($array as $key=>$value)
{
switch($key)
{
case "txtFSPLongRuban":
//This is the important stuff HERE.....
if(preg_match('#^false.*$#', $value))//If false do nothing
{}
else if(!preg_match('#^true[1-9][0-9]*$#', $value))//Check if true and if number higher than 0.
{
//Do stuff,
//Some more stuff
//Just a bit more stuff...
//Done! No more stuff to do.
}
break;
//Many more cases...
}
}
}
正如您所看到的,我使用regEx将trought解析为字符串。但它与十进制数字不匹配。
我知道如何做regEx来解析十进制,这不是问题所在。
问题是:
php中是否已经有一个函数与我需要的解析相匹配?
如果没有,你们中有人知道更有效的解析方法吗?还是我应该在regEx中添加小数部分?
我在想:
test = str_split($value, "true")
if(isNumeric(test[1]) && test[1] > 0)
//problem is that isNumeric accepte hex and a cant have letter in there only straight out int or decimal number higher than 0.
知道吗??
非常感谢你的帮助!
使用substr
:文档
if(substr($value, 0, 4) == "true"){
$number_part = substr($value, 5);
if(((int) $number == $number) || ((float) $number == $number)){
//do something...
}
}
您可以这样做:
case "txtFSPLongRuban":
if (preg_match('~^true(?=.*[^0.])([0-9]+(?:'.[0-9]+)?)$~', $value, $match))
{
// do what you want with $match[1] that contains the not null number.
}
break;
预视(?=.*[^0.])
检查是否有不是0
或.
的字符
这应该做到这一点,并处理两种类型的值:
preg_match('/^(true|false)(.*)$/', $value, $matches);
$real_val = $matches[2];
if ($matches[1] == 'true') {
... true stuff ...
} else if ($matches[1] == 'false') {
... false stuff ...
} else {
... file not found stuff ...
}
试试:
else if(!preg_match('#^true([1-9][0-9]*(?:'.[0-9]*)?$#', $value))
查看ctype_digt:
Checks if all of the characters in the provided string, text, are numerical.
要检查小数,可以使用filter_var
:
if (filter_var('123.45', FILTER_VALIDATE_FLOAT) !== false) {
echo 'Number';
}