如何用数组术语替换

时间:2014-03-10 16:04:55

标签: php str-replace

我需要替换文字中的单词

    $test = "Nordman Nokian NORDMAN 4 XL";
$replaces = array("Amtel " ,"Bridgestone " ,"Continental " ,"Cordiant " ,"Dunlop " ,"Formula " ,"Gislaved " ,"Kingstar " ,"BFGoodrich " ,"GoodYear " ,"Hankook " ,"Headway " ,"Fulda " ,"HIFLY " ,"Kumho " ,"Gremax " ,"Matador " ,"Michelin " ,"Rosava " ,"Nankang " ,"Nokian " ,"Nordman Nokian " ,"Pirelli " ,"Radial " ,"Sava " ,"Tigar " ,"Toyo " ,"Viatti " ,"Maxxis " ,"Yokohama ");
echo str_replace($replaces, "", $test);
// return Nordman NORDMAN 4 XL

所需的结果

// return NORDMAN 4 XL

我为有问题的更改道歉,添加了无法替换的代码

3 个答案:

答案 0 :(得分:0)

您的array

中有拼写错误
$replaces = array("Hellow world","Like");

现在str_replace返回this

答案 1 :(得分:0)

参考 - http://in1.php.net/manual/en/function.str-replace.php

这里,数组是我们要替换的单词,第二个参数是我们要替换的字符串,第三个参数是字符串的大海捞针。这应该工作

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

答案 2 :(得分:0)

您的问题是您在字符串Nokian之前替换了字符Nordman Nokian。由于首先匹配单个词Nokian,因此该字符串将转换为Nordman NORDMAN 4 XL,而str_replace无法匹配字符串Nordman Nokian。只需切换数组项的顺序

即可

即。 ..."Nordman Nokian ","Nokian "...