2015-06-19 26 views
0

我已经从网站上刮掉了一个html字符串。在此字符串中,它包含多个字符串,如color:#0269D2。我怎样才能让str_replace代码替换这个字符串与另一个color替换字符串中的多个项目

例如像这样只是循环遍历所有color:#0269Dfulltext字符串变量?

str_replace("color:#0269D","color:#000000",$fulltext); 
+0

您不必遍历更换同一事物的所有实例。从str_replace手册中,“str_replace - 用替换字符串替换所有出现的搜索字符串” –

回答

0

你传递数组str_replace函数功能,无需使用循环

$a= array("color:#0269D","color:#000000"); 

$str= str_replace($a,"", $string); 
0

你有正确的语法。我会添加一个支票:

$newText = str_replace("color:#0269D", "color:#000000", $fulltext, $count); 
if($count){ 
    echo "Replaced $count occurrences of 'color'."; 
} 

此代码可能对您要做的事情太贪婪。小心。另外,如果字符串完全不同,例如color: #0269D,则不会发生此替换。

0

'str_replace'已经用替换字符串替换了所有出现的搜索字符串。

如果您要更换所有的颜色,但不知道哪个hexcodes你会发现你可以使用preg_replace匹配一个模式的多次出现用正则表达式和替换它。

你的情况:

$str = "String with loads of color:#000000"; 
$pattern = '/color ?: ?#[0-9a-f]{3,6}/i'; 
$replacement = "color:#FFFFFF"; 
$result = preg_replace($pattern, $replacement, $str);