Harinder
Harinder

Reputation: 1257

Multiple preg_match to check result in Multiple Lines

I want to check preg_match with multiple $line... here is my code

$line = "Hollywood Sex Fantasy , Porn";
if (preg_match("/(Sex|Fantasy|Porn)/i", $line)){
echo 1;}else {echo 2;}

now i want to check in many likes some thing like

$line = "Hollywood Sex Fantasy , Porn";
if (preg_match("/(Sex|Fantasy|Porn)/i", $line, $line1, $line2)){
echo 1;}else {echo 2;}

something like above code with $line1 $line2 $line3

Upvotes: 1

Views: 350

Answers (5)

BlitZ
BlitZ

Reputation: 12168

$lines = array($line1, $line2, $line3);
$flag  = false;

foreach($lines as $line){
   if (preg_match("/(Sex|Fantasy|Porn)/i", $line)){
      $flag = true;
      break;
   }
}

unset($lines);

if($flag){
   echo 1;
} else {
   echo 2;
}
?>

You might convert it to a function:

function x(){
    $args  = func_get_args();

    if(count($args) < 2)return false;

    $regex = array_shift($args);

    foreach($args as $line){
       if(preg_match($regex, $line)){
          return true;
       }
    }

    return false;
}

Usage:

x("/(Sex|Fantasy|Porn)/i", $line1, $line2, $line3 /* , ... */);

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173642

If just one line has to match, you can simply concatenate the lines into a single string:

if (preg_match("/(Sex|Fantasy|Porn)/i", "$line $line1 $line2")) {
    echo 1;
} else {
    echo 2;
}

This works like an OR condition; match line1 or line2 or line3 => 1.

Upvotes: 3

sectus
sectus

Reputation: 15464

Crazy example. Using preg_replace instead of preg_match :^ )

$lines = array($line1, $line2, $line3);
preg_replace('/(Sex|Fantasy|Porn)/i', 'nevermind', $lines, -1, $count);
echo $count ? 1 : 2;

Upvotes: 0

AbsoluteƵER&#216;
AbsoluteƵER&#216;

Reputation: 7880

<?php
    //assuming the array keys represent line numbers
    $my_array = array('1'=>$line1,'2'=>$line2,'3'=>$line3);
    $pattern = '!(Sex|Fantasy|Porn)!i';

    $matches = array();
    foreach ($my_array as $key=>$value){
      if(preg_match($pattern,$value)){
            $matches[]=$key;  
      }
    }

    print_r($matches);

?>

Upvotes: 1

Suhel Meman
Suhel Meman

Reputation: 3852

$line = "Hollywood Sex Fantasy , Porn";

if ((preg_match("/(Sex|Fantasy|Porn)/i", $line) && (preg_match("/(Sex|Fantasy|Porn)/i", $line1) &&  (preg_match("/(Sex|Fantasy|Porn)/i", $line2))
{
    echo 1;
}
else
{
    echo 2;
}

Upvotes: 0

Related Questions