PHP:str_replace仅替换第一次出现

时间:2012-06-26 08:28:19

标签: php

这段代码有没有人知道为什么只有第一个$unuseful字被替换为字符串?

$unuseful = array(" is ", " the ", " for ", " and ", " with "," that ", " this "," or ", ",",";","/","?","!",".");
$aux = str_replace($unuseful, " " , $statement);

“花花公子把这个家伙解雇了” - >花花公子免费花花公子

“花花公子把这个家伙解雇了” - >花花公子免费花钱了

提前致谢!

3 个答案:

答案 0 :(得分:4)

那是因为你设置了前导和尾随空格。

它取代了“the”一次,因为“the”只有3个空格,而你正在寻找替换4。

答案 1 :(得分:2)

    for($i=0;$i<count($unuseful);$i++)
    {$statement = str_replace($unuseful[$i], " " , $statement);}
$aux=$statement;

答案 2 :(得分:1)

<?php
$unuseful = array('/\s+is\s+/', '/\s+the\s+/', '/\s+for\s+/', '/\s+and\s+/', '/\s+with\s+/','/\s+that\s+/', '/\s+this\s+/','/\s+or\s+/', '/,/','/;/','/\//','/\?/','/\!/','/\./');

$challenge = 'dude cost that free the dude the the';
echo preg_replace($unuseful, ' ', $challenge)."\n";
?>

给出:

花花公子免费花钱