2017-11-07 18 views
1

php関数は悪い単語を開始に置き換えるために使用されていますが、悪い単語が見つかったかどうかを示す1つの追加パラメータが必要です。PHPの悪い言葉の星と出力配列の置換

$badwords = array('dog', 'dala', 'bad3', 'ass'); 
    $text = 'This is a dog. . Grass. is good but ass is bad.'; 
    print_r(filterBadwords($text,$badwords)); 


    function filterBadwords($text, array $badwords, $replaceChar = '*') { 
$repu = preg_replace_callback(array_map(function($w) { return '/\b' . preg_quote($w, '/') . '\b/i'; }, $badwords), 
     function($match) use ($replaceChar) { 
        return str_repeat($replaceChar, strlen($match[0])); }, 
        $text 

        ); 
return array('error' =>'Match/No Match', 'text' => $repu); 
}// Func 

出力見つかっBADWORDSが

アレイのようにする必要がある場合([エラー] =>マッチ[テキスト] =>バート・ワード犬マッチ。)

何BADWORDSが見つからない場合

アレイ([エラー] =>ノーマッチ[テキスト] =>バート・ワードマッチ。)

+0

れ基づいて? – Sucharitha

+1

$ textの単語が$ badwordsと一致する場合は、この単語が悪いことを意味します –

+1

あなたはどんな問題に直面していますか? –

答えて

1

次を使用することができます。

function filterBadwords($text, array $badwords, $replaceChar = '*') { 
    //new bool var to see if there was any match 
    $matched = false; 
    $repu = preg_replace_callback(array_map(
     function($w) 
     { 
      return '/\b' . preg_quote($w, '/') . '\b/i'; 
     }, $badwords), 
     //pass the $matched by reference 
     function($match) use ($replaceChar, &$matched) 
     { 
      //if the $match array is not empty update $matched to true 
      if(!empty($match)) 
      { 
       $matched = true; 
      } 
      return str_repeat($replaceChar, strlen($match[0])); 
     }, $text); 
    //return response based on the bool value of $matched 
    if($matched) 
    { 
     $return = array('error' =>'Match', 'text' => $repu); 
    } 
    else 
    { 
     $return = array('error' =>'No Match', 'text' => $repu); 
    } 
    return $return; 
} 

これは、任意の一致があったかどうかを確認するためにreferenceif条件を使用して、それに基づいて応答を返します。 (一致した場合)

出力:

array (size=2) 
    'error' => string 'Match' (length=5) 
    'text' => string 'This is a ***. . Grass. is good but *** is bad.' 

出力(どれもマッチしていない場合):あなたが悪い単語として文字列を決定することができます

array (size=2) 
    'error' => string 'No Match' (length=8) 
    'text' => string 'This is a . . Grass. is good but is bad.' 
+1

wao。どのような素晴らしい解決策 –

0
<?php 
$badwords = array('dog', 'dala', 'bad3', 'ass'); 
$text = 'This is a dog. . Grass. is good but ass is bad.'; 
$res=is_badword($badwords,$text); 
echo "<pre>"; print_r($res); 


function is_badword($badwords, $text) 
{  
    $res=array('No Error','No Match'); 
    foreach ($badwords as $name) { 
     if (stripos($text, $name) !== FALSE) { 
      $res=array($name,'Match'); 
      return $res; 
     } 
    } 
    return $res; 
} 

?> 

Output: 

Array 
(
    [0] => dog 
    [1] => Match 
)