簡體   English   中英

如何計算字符串中的char並使用PHP進行驗證

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

我想以必須包含2個連字符(-)的方式驗證字符串

字符串輸入 :(例如)

B405Q-0123-0600

B405Q-0123-0612

R450Y-6693-11H0

R450Y-6693-11H1

像這樣利用substr_count函數

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

將導致

2
0

像這樣驗證

if(substr_count( $some_string, "-" ) == 2)
{
       echo 'true';
       // do something here
}else
{
       echo 'false validation failed';
       // some error handling
}

如果您的字符串如圖所示,那么您可以

$re = "/(\\w{5}-\\w{4}-\\w{4})/"; 
$str = "B405Q-0123-0600"; // Your strings
if (preg_match($re, $str, $matches)) {
   // valid
} else {
   // invalid
}

我只需要檢查字符串是否有兩個連字符

如果只想檢查在任何地方是否有兩個連字符,則可以在連字符上拆分字符串。 如果只有兩個連字符,那么將有3個拆分部分。

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

為了檢查這種類型的驗證,您需要使用javascript的Regex。 使用以下給定的正則表達式。

var check="^\w+([\s\-]\w+){0,2}$";

現在,所有需要的就是通過創建javascript函數進行檢查,您已經完成了一半。

嘗試這個:

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

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

使用下面的代碼

  $string = "B405Q-0123-0612";

    $arr = explode("-",$string)

    if (count($arr) == 2)
    {
        //yes you have 2 hyphens
    }

上面的過程是最簡單的方法

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