Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 648
Ryan Cooper Avatar asked May 10 '11 19:05

Ryan Cooper


1 Answers

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

like image 197
FrustratedWithFormsDesigner Avatar answered Sep 28 '22 03:09

FrustratedWithFormsDesigner