简体   繁体   中英

How to combine two conditional statements in PHP

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;

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".

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 !== .

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?

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM