簡體   English   中英

PHP-正則表達式需要幫助

[英]PHP - Regular Expressions Help Needed

我有聯系表,我需要過濾一些單詞。

我這樣做如下:

$array = array('lorem', 'ipsum', 'ip.sum');
for($i = 0; $i < count($array); $i++)
        {
            if( preg_match("/".$array[$i]."/", (string) $field) )
            {
                return false;
            }
        }

我不是正則表達式大師,但它應該適用於lorem或ipsum之類的單詞。 但事實並非如此。

BTW。 關於如何捕獲拼寫錯誤的單詞的任何建議,例如。 i.psum,lorem?

更新
當然,我沒有空模式,只是忘了粘貼它。

更新2
我已決定采用Daniel Vandersluis提出的建議。 Abnyway,我無法使其正常運行。

$field = "ipsum lorem"; // This value comes from textarea
$array = array('ipsum', 'lorem', 'ip.sum');
foreach($array as $term):
    if(preg_match('/'.preg_quote($term).'/', $field)) {
        return false;
    }
endforeach;

有任何想法嗎?

如果我理解正確,並且想查看數組中是否有任何單詞在字段中,則可以執行以下操作:

function check_for_disallowed_words($text, $words)
{
  // $text is the text being checked, $words is an array of disallowed words
  foreach($words as $word)
  {
    if (preg_match('/' . preg_quote($word) . '/', $text))
    {
      return false;
    }
  }

  return true;
}

$array = array('lorem', 'ipsum', 'ip.sum');
$valid = check_for_disallowed_words($field, $array);

在您的示例中,您沒有定義要使用的任何模式。 preg_quote將接受一個字符串並使其准備在正則表達式中使用(例如,因為ip.sum的點在正則表達式中實際上具有特殊含義 ,因此如果要搜索文字點,則需要轉義該字符串)。

順便說一句,如果您想了解有關正則表達式的更多信息,請看一下regular-expressions.info上的教程 ,它非常深入。

您不需要正則表達式即可進行簡單的單詞過濾。

function is_offensive($to_be_checked){
   $offensive = array('lorem', 'ipsum', 'ip.sum');
   foreach($offensive as $word){
      if(stristr($to_be_checked, $word) !== FALSE){
          return FALSE;
      }
   }
}

用法:

$field = $_POST['field'];
if(is_offensive($field)){
   echo 'Do not curse on me! I did not crash your computer!';
}
else{
    //make the visitor happy
}

我這樣為我翻譯了您的問題: 我如何通過一組正則表達式替換變量中的單詞。

您可以嘗試以下方法:

 $array = array('lorem', 'ipsum', 'ip.sum', '');

 $field = preg_replace("/(" . implode(")|(", $array) . ")/i", "--FILTERED-OUT--", (string) $field));

它根據$array元素構造最終的正則表達式。 這樣就可以將單詞指定為正則表達式(ip.sum〜ip [whatever character] sum)。 標志i用於不區分大小寫的搜索。

更改

if( preg_match("//", (string) $field) )

if( preg_match("/$array[$i]/", (string) $field) )

另一個變體,也許有一定用處(您沒有非常徹底地說明問題):

根據用戶評論編輯

 // comparison function
 function check_field_in($field, $phrases)
{
 foreach($phrases as $phrase) {
    $match_text = quotemeta($phrase);            // if this works, 
    if( preg_match("/^$match_text$/", $field) )  // this part can be optimized
       return false;                             
 }
 return true;
}

// main program goes here
 $textarea = 'lorem ipsum  i.psum l.o.rem';

 foreach(preg_split('/\s+/', $textarea) as $field) {
    if( check_field_in( $field, array('lorem','ipsum') ) == true )
       echo "$field OK\n";
    else
       echo "$field NOT OK\n";
 }

這將打印:

lorem NOT OK
ipsum NOT OK
i.psum OK
l.o.rem OK

問候

RBO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM