2015-06-21 60 views
2

如何從文本中替換或過濾不良詞語,如str_ireplace? 我需要從數組中替換單詞中的值,但不使用foreach和爆炸。PHP將單詞從鍵值替換爲數組中的值

例陣列

$_filter = [ 
    'badwords' => [ 
    'one'     => 'time', 
    'bad'     => 'good', 
    'ugly'     => 'beauty' 
    ] 
]; 

實施例替換

$before = 'anyone help me please'; 
$after = 'anytime help me please'; 

$before = 'I need BaD function'; 
$after = 'I need good function'; 

$before = 'I am so (ugly)'; 
$after = 'I am so (beauty)'; 

試圖these但不工作。 任何人都可以幫助我。謝謝

回答

0

我會用一個簡單的str_replace

<?php 
    $search = array('one', 'bad', 'ugly'); 
    $replace = array('time', 'good', 'beauty'); 
    $before = 'anyone help me please'; 
    echo str_replace($search, $replace, $before); 
    $before = 'I need bad function'; 
    echo str_replace($search, $replace, $before); 
    $before = 'I am so (ugly)'; 
    echo str_replace($search, $replace, $before); 

這裏的Eval

3

功能str_ireplace()將根據其文檔接受數組作爲第一,第二和第三個參數:

http://php.net/manual/en/function.str-ireplace.php

使用函數array_keys(),您可以獲得您的所有密鑰過濾器數組作爲第一個參數傳遞它們。然後你只需要傳遞數組作爲第二個參數,並將字符串作爲第三個參數。

代碼示例:

$filter = [ 
    'badwords' => [ 
    'one' => 'time', 
    'bad' => 'good', 
    'ugly' => 'beauty' 
    ] 
]; 

$before = 'anyone help me please'; 

$after = str_ireplace(array_keys($filter['badwords']), $filter['badwords'], $before); 

echo $after; 

而你的輸出將是:

anytime help me please 
+0

謝謝你,array_keys是我的問題,完善功能 – Baron