2016-07-11 73 views
1

如果字符串有特定的結構,如何用php與preg_match()進行檢查。例如字符串是:preg_match來檢查字符串是否有特定的結構

options:blue;white;yellow; 

我要檢查,如果字符串與字符串,然後:隨後通過;

分隔的字符串的正數和東西是重要的開始 - 字符串可以採用西裏爾字母,不僅拉丁字母

+0

用';'分隔的特定數量的字符串?編碼UTF-8? – Will

+0

是的,utf-8是編碼 – Europeuser

+0

字符串是否可以包含數字或符號? – Will

回答

1

假設只有在你的問題中所列的限制都需要,這將驗證字符串:

$number = 3; 
$regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number); 

if (preg_match($regex, $string)) { 
    echo "It matches!"; 
} else { 
    echo "It doesn't match!"; 
} 

下面是它在行動的例子,用php -a

php > $number = 3; 
php > $regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number); 

php > if (preg_match($regex, 'options:blue;white;yellow;')) { 
php {  echo "It matches!"; 
php { } else { 
php {  echo "It doesn't match!"; 
php { } 
It matches! 

php > if (preg_match($regex, 'options:blue;white;yellow;green;')) { 
php {  echo "It matches!"; 
php { } else { 
php {  echo "It doesn't match!"; 
php { } 
It doesn't match! 

你可以想像這個表達式here。讓我們來分解它:

/.../   Start and end of the pattern. 
^    Start of the string. 
[^:]+   At least one character that is not a ':'. 
:    A literal ':'. 
(?:[^;]+;){N} Exactly N occurrences of: 
        [^;]+ At least one character that is not a ';'. 
        ;  A literal ';'. 
$    End of the string. 
+0

#會,我測試後,我可以確認它分開工作。我認爲$ number = 3定義了選項的數量,但正如我所說的那樣,它會有n個選項使得任務更加複雜,不是嗎? – Europeuser

+0

我不明白......'$ number'是你的'n'。如果您事先知道需要多少,請將'$ number'設置爲該數字。或者,你的意思是你不知道'n'會是什麼? – Will

+0

是的,但我通過改變它來解決:$ number = count(explode(';',rtrim($ _ POST ['addoptions'],「;」)));它按預期工作,謝謝! – Europeuser

相關問題