简体   繁体   中英

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(-)

Strings input : (for eg)

B405Q-0123-0600

B405Q-0123-0612

R450Y-6693-11H0

R450Y-6693-11H1

Make use of substr_count function like this

<?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.

$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. 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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