How to combine two IF statements in PHP

自作多情 提交于 2020-01-01 02:46:07

问题


Okay i know this is a newb question, but how would i go about only performing IF 2 if IF 1 (text: test appears in data string.) I've tried combining the two but end up with all sorts of issues. So if test doesnt show up the loops skipped, if it does then the regex code i have in IF 2 will be ran.

$data = 'hello world "this is a test" last test';


// IF 1 
if (stripos($data, 'test') !== false) {
}


// IF 2
if (preg_match('/"[^"]*"/i', $data, $regs)) {
$quote = str_word_count($regs[0], 1);
$data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
}

echo $data;

回答1:


Either:

if (stripos($data, 'test') !== false) {
    if (preg_match('/"[^"]*"/i', $data, $regs)) {
        $quote = str_word_count($regs[0], 1);
        $data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
    }
}

Or:

if (stripos($data, 'test') !== false && preg_match('/"[^"]*"/i', $data, $regs)) {
    $quote = str_word_count($regs[0], 1);
    $data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
}

Both do the same thing. The && operator means "and". The || operator means "or".




回答2:


Do you mean you want to nest one inside the other?

if (stripos($data, 'test') !== false)
{

  if (preg_match('/"[^"]*"/i', $data, $regs))
  {
     $quote = str_word_count($regs[0], 1);
     $data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
  }

}

You could also change this to use && (which means "And"):

if (stripos($data, 'test') !== false && preg_match('/"[^"]*"/i', $data, $regs)) {
            $quote = str_word_count($regs[0], 1);
            $data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
}

Also, your code uses !==. Is that what you meant or did you mean !=? I believe they have different meanings - I know that != means "Not equal" but I'm not sure about !==.




回答3:


Simply nest your IF statements

if (stripos($data, 'test') !== false) {
    if (preg_match('/"[^"]*"/i', $data, $regs)) {
        $quote = str_word_count($regs[0], 1);
        $data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
    }

}

Or have I misunderstood your question?

Saying "I've tried combining the two but end up with all sorts of issues" is quite vague. Combining how? Nested like this? What issues?




回答4:


if (stripos($data, 'test') !== false) {
  if (preg_match('/"[^"]*"/i', $data, $regs)) {
  $quote = str_word_count($regs[0], 1);
  $data = str_replace($regs[0], '"'.implode(' ', $quote).'"', $data);
  }
}


来源:https://stackoverflow.com/questions/5955678/how-to-combine-two-if-statements-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!