0

这是行不通的,发生了什么应该很简单:-(

    $test = "hello naughty";


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

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

}

echo $post;

谢谢

4

6 回答 6

3

您(总是)使用 $test 作为输入参数。
在示例notallowed中,foreach 循环的第二次迭代中的指针未找到,因此输入字符串原样$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>

于 2012-11-08T10:31:29.743 回答
1

您可以直接使用数组进行替换

<?php

    $test = "hello naughty";
    $swearWords = array("naughty","notallowed");
    $post = str_ireplace($swearWords, "<b><i>(oops)</i></b>", $test);
    echo $post;
?>
于 2012-11-08T10:32:56.933 回答
1

采用

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

反而。有关函数处理数组参数的方式的信息,请参见str_ireplace 。

于 2012-11-08T10:33:05.633 回答
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>";

}

尝试编辑的代码

于 2012-11-08T10:34:32.717 回答
0

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

愿这些对您有所帮助并解决您的问题。

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

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

谢谢。

于 2012-11-08T10:46:15.607 回答
-1

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

于 2012-11-08T10:32:24.750 回答