2013-04-16 35 views
0

我要检查的preg_match多$线检查结果...这里是我的代码多的preg_match以多行

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

现在我想在很多检查喜欢就好

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

像上面的代码与$line1 $line2 $line3

+0

你是如何得到'$ line1'和'$ line2'?你可以把一切都放在一个单独的字符串中。 –

+0

@Jack我正在用$ like和$ line1检查不同的东西,比如名称,流派等...所以我想检查这些东西并给出输出会计 – Harinder

+0

正则表达式是否应匹配所有行或任何行? –

回答

3

如果只有一条线路必须匹配,你可以简单地将线连接成一个字符串:

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

该作品像OR条件一样;匹配line1或line2或line3 => 1.

1
$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; 
} 
?> 

你可以将其转换为一个函数:

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

用法:

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

你ans是非常好的... thx ..但杰克和套房我的要求... thx任何方式;) – Harinder

+0

你不客气:) – BlitZ

0
$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; 
} 
1
<?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); 

?> 
0

疯狂的例子。使用preg_replace而不是preg_match:^)

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