首页 > 解决方案 > 使用 str_replace 时出现多个数组错误

问题描述

我想替换如下文本。

$text = '<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre><code>[[EXAMPLE]] this is a text. <br />[[EXAMPLE2]]</code></pre>
<p style="text-align: center;"><br /><br /></p>
</body>
</html>';


$products['type'] = 1;
$products['quantity'] = 2300.0;
$products['grade'] = null;

 $searchVal = array(
'[[EXAMPLE]]'
'[[EXAMPLE2]]'
);

 $replaceVal = array(
'replace word',
 $products
); 

$text = str_replace($searchVal, $replaceVal, $text);

我没有运行这段代码。这个失败是“数组到字符串的转换”

我怎样才能做到这一点。

标签: phplaravelstr-replace

解决方案


根据文档

如果搜索和替换是数组,则 str_replace() 从每个数组中获取一个值并使用它们来搜索和替换主题

确保两者$searchVal都是$replaceVal线性阵列,目前它们不是。

您的$searchVal定义缺少逗号。

$replaceVal是一个数组,其中第二个元素是另一个数组。


推荐阅读