如果语句为真,则存储内容

时间:2015-12-30 21:47:28

标签: php if-statement

这是一个我无法弄清楚的简单代码

if(preg_match(  "/where/","where's my backpack") == true){
    echo "this is a match";
    // this is the part i cant figure out
    // how can I store it as == $match1
    // I tried $match1 == "this is a match"; but it didn't work   

}else{
    //$match1= " "; << this what I tried and didn't work
    //when I say echo match1 later, it displays this is a match even when its wrong
}

如何将其存储为变量或其他东西以供日后使用。例如,如果这两个匹配为真,则将其存储为$ match1,以便稍后我可以说'echo $ match1',以便显示“这是匹配”。如果不只是展示空间。

整体代码在php BTW

2 个答案:

答案 0 :(得分:2)

==运算符检查是否相等,以存储您需要使用的内容=

$match1 = '';
if(preg_match("/where/", "where's my backpack"))
    $match1 = "this is a match";
else
    $match1 = " ";
echo $match1;

答案 1 :(得分:0)

您可以直接分配:

$match = preg_match("/where/","where's my backpack") === 1

现在你有一个布尔值,你可以在这个语句之后的任何地方使用它。

请注意,我已将true替换为1,因为preg_match将返回,但这两种方法都有效。

顺便说一句,我意识到这不是你想要的,但是当我将输出文本与逻辑分开时,我发现它更易于维护和更可重用。