2012-11-08 57 views
0

這不是工作,這是怎麼回事,應該是這麼簡單:-(PHP的字符串替換難倒我

$test = "hello naughty"; 


$swearWords = array("naughty","notallowed"); 

foreach ($swearWords as $naughty) 
{ 
    $post = str_ireplace($naughty, "<b><i>(oops)</i></b>", $test); 

} 

echo $post; 

感謝

+0

'$ post'或'$ test'? – Dogbert

+0

如果有疑問,請在腳本中的每個步驟輸出每個相關變量。這會使問題在這種情況下非常明顯。 – deceze

回答

3

你(總是)使用$測試作爲輸入參數。
在foreach循環的第二次迭代的針notallowed的例子中沒有找到,並且因此輸入字符串$test='hello naughty'原封不動地返回。

<?php 
$test = "hello naughty"; 
$swearWords = array("naughty","notallowed"); 

$post = $test; 
foreach ($swearWords as $naughty) 
{ 
    $post = str_ireplace($naughty, "<b><i>(oops)</i></b>", $post); 
} 

echo $post; 

打印hello <b><i>(oops)</i></b>

和str_ireplace可以採取針陣列作爲第一參數

<?php 
$test = "hello notallowed, this is naughty"; 
$post = str_ireplace(array("naughty","notallowed"), "<b><i>(oops)</i></b>", $test); 
echo $post; 

打印hello <b><i>(oops)</i></b>, this is <b><i>(oops)</i></b>

+0

是的,我現在看到了問題,我正在沉默...... – Lee

-1

$ swearWords = array(「naughty」); 然後它說(哎呀)而不是淘氣。

1

您可以直接使用陣列更換

<?php 

    $test = "hello naughty"; 
    $swearWords = array("naughty","notallowed"); 
    $post = str_ireplace($swearWords, "<b><i>(oops)</i></b>", $test); 
    echo $post; 
?> 
1

使用

$test = "hello naughty"; 
$swearWords = array("naughty","notallowed"); 
$post = str_ireplace($swearWords,"<b><i>(oops)</i></b>",$test) 
echo $post; 

代替。有關函數處理數組參數的方式,請參閱str_ireplace

1

嘗試用這種

$test = "hello naughty"; 


$swearWords = array("naughty","notallowed"); 

foreach ($swearWords as $naughty) 
{ 
//$post = str_ireplace($naughty, "(oops)", $test); 
echo str_ireplace($naughty,"<b><i>(oops)</i></b>",$test)."<br>"; 

} 

嘗試編輯的代碼

+0

不,你有你的參數錯誤的方式。 –