我如何计算字符串中的char并使用PHP进行验证
I want to validate a string in such a way that in must have 2 hypens(-)
Strings input : (for eg)
B405Q-0123-0600
B405Q-0123-0612
R450Y-6693-11H0
R450Y-6693-11H1
我想以这样一种方式验证字符串,即必须有2个超量( - ) p> \ n
字符串输入 strong> :(例如) p>
B405Q-0123-0600
B405Q-0123-0612
\ nR450Y-6693-11H0
R450Y-6693-11H1
code> pre>
div>
Make use of substr_count function like this
<?php
echo substr_count( "B405Q-0123-0600", "-" )."
";
echo substr_count( "B405Q01230600", "-" )."
";
?>
Will Result
2
0
Validate like this
if(substr_count( $some_string, "-" ) == 2)
{
echo 'true';
// do something here
}else
{
echo 'false validation failed';
// some error handling
}
If your strings are like shown, then you can do
$re = "/(\\w{5}-\\w{4}-\\w{4})/";
$str = "B405Q-0123-0600"; // Your strings
if (preg_match($re, $str, $matches)) {
// valid
} else {
// invalid
}
I just need to check if the string is having two hyphens
If you only want to check if there are two hyphens anywhere, then you can split your strings on hyphens. If there are two and only two hyphens, then there will be 3 split parts.
$str = "B405Q-0123-0600"; // your strings
if (count(split("-", $str)) === 3) {
// two hyphens present
} else {
// not enough hyphens
}
Try this:
var str = "B405Q-0123-0612";
var arr = str.split("-");
if(arr.length=3){
alert("Your string contain 2 hyphens");
}
For checking this type of validation you are required to use the Regex of javascript. Use below given regular expression.
var check="^\w+([\s\-]\w+){0,2}$";
Now all need is to check this with creating the javascript function and you are half the way there.
use the below code
$string = "B405Q-0123-0612";
$arr = explode("-",$string)
if (count($arr) == 2)
{
//yes you have 2 hyphens
}
The above procedure is the simplest way to do
preg_match_all("/\-/",'B405Q-0123-0600',$match);
if(count($match[0]) == 2){
// valid
}else{
// invalid
}