2013-04-16 36 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;