簡體   English   中英

在if語句條件中使用正則表達式

[英]using regular expressions in if statement conditions

我試圖獲得一個php if語句,如果一個set變量等於“view - ##”,其中#表示任何數字。 設置具有該條件的if語句的正確語法是什么?

if($variable == <<regular expression>>){
    $variable2 = 1;
}
else{
    $variable2 = 2;
}

使用preg_match()函數:

if(preg_match("/^view-\d\d$/",$variable)) { .... }

[編輯] OP另外詢問他是否可以隔離這些數字。

在這種情況下,您需要(a)在正則表達式中的數字周圍放置括號,以及(b)向preg_match()添加第三個參數。

第三個參數返回正則表達式找到的匹配項。 它將返回一個匹配數組:數組的元素零將是整個匹配的字符串(在您的情況下,與輸入相同),數組的其余元素將匹配表達式中的任何括號集。 因此$matches[1]將是你的兩位數:

if(preg_match("/^view-(\d\d)$/",$variable,$matches)) {
     $result = $matches[1];
}

你應該使用preg_match 例:

if(preg_match(<<regular expression>>, $variable))
{
 $variable1 = 1;
}
else
{
  $variable2 = 2;
}

如果您只做一項任務,還要考慮三元運算符

$variable2 = preg_match(<<regular expression>>, $variable) ? 1 : 2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM