我有一个包含2个信息的字符串(1.A布尔/ 2.Something(可以是数字,字母,特殊字符,可以是任意长度)。)
2是用户输入。
Exemples:
(part 1)"true".(part 2)"321654987" => "true321654987"
也可以
"false321654987" or "trueweiufv2345fewv"
我需要的是一种解析字符串的方法,首先检查1是true
(如果它不做什么),如果它是true
我需要检查是否跟随部分是一个高于0的正数(必须接受任何高于0的数字,即使是十进制,但不是二进制或十六进制(好......可能是10,但它的意思是10而不是两个))。
以下是我的尝试:
//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来解析字符串。但它确实与十进制数匹配。
我知道如何使用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.
任何想法??
非常感谢您的帮助!
答案 0 :(得分:1)
使用substr
:documentation
if(substr($value, 0, 4) == "true"){
$number_part = substr($value, 5);
if(((int) $number == $number) || ((float) $number == $number)){
//do something...
}
}
答案 1 :(得分:1)
你可以这样做:
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
或.
答案 2 :(得分: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 ...
}
答案 3 :(得分:0)
尝试使用:
else if(!preg_match('#^true([1-9][0-9]*(?:\.[0-9]*)?$#', $value))
答案 4 :(得分:0)
查看ctype_digit:
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';
}