php字符串替换困惑我

时间:2012-11-08 10:28:22

标签: php string str-replace

这不起作用,发生的事情应该是这么简单: - (

    $test = "hello naughty";


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

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

}

echo $post;

由于

6 个答案:

答案 0 :(得分:3)

您(总是)使用$ test作为输入参数 在示例中,未找到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>

答案 1 :(得分:1)

您可以直接使用数组替换

<?php

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

答案 2 :(得分:1)

使用

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

代替。有关函数处理数组参数的方式的信息,请参阅str_ireplace

答案 3 :(得分: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>";

}

尝试编辑代码

答案 4 :(得分:0)

支持其他答案我有几个链接,显示了可以帮助你的例子。

这些对你有帮助并解决你的问题。

http://www.w3schools.com/php/func_string_str_ireplace.asp

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

感谢。

答案 5 :(得分:-1)

$ swearWords = array(“naughty”); 然后它说(哎呀)而不是顽皮。