简体   繁体   English

如何计算字符串中的char并使用PHP进行验证

[英]How I can count char in a string and validate using PHP

I want to validate a string in such a way that in must have 2 hypens(-) 我想以必须包含2个连字符(-)的方式验证字符串

Strings input : (for eg) 字符串输入 :(例如)

B405Q-0123-0600

B405Q-0123-0612

R450Y-6693-11H0

R450Y-6693-11H1

Make use of substr_count function like this 像这样利用substr_count函数

<?php
 echo substr_count( "B405Q-0123-0600", "-" )."\n";
 echo substr_count( "B405Q01230600", "-" )."\n";
?>

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. 如果只有两个连字符,那么将有3个拆分部分。

$str = "B405Q-0123-0600"; // your strings
if (count(split("-", $str)) === 3) {
   // two hyphens present
} else {
   // not enough hyphens
}

For checking this type of validation you are required to use the Regex of javascript. 为了检查这种类型的验证,您需要使用javascript的Regex。 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. 现在,所有需要的就是通过创建javascript函数进行检查,您已经完成了一半。

Try this: 尝试这个:

var str = "B405Q-0123-0612";
var arr = str.split("-");

if(arr.length=3){
    alert("Your string contain 2 hyphens");
}

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM