str_ireplace 不适用于单引号
我想替换字符串中的单引号 (')。
显然这行不通......:
$patterns = array();
$replacements = array();
$patterns[0] = "'";
$patterns[1] = '\'';
$replacements[0] = 'Something';
$replacements[2] = 'Same thing just in a other way';
I want to replace single quote (') in a string.
Apparently this will not work...:
$patterns = array();
$replacements = array();
$patterns[0] = "'";
$patterns[1] = '\'';
$replacements[0] = 'Something';
$replacements[2] = 'Same thing just in a other way';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 (
'
) 替换为 ("
) 对于我来说效果很好,str_ireplace
。也可以将 (
"
) 替换为 ('< /代码>)
Replacing (
'
) with ("
) works fine for me withstr_ireplace
.Also works fine replacing (
"
) with ('
)看起来你的示例代码已经过度匿名($replacements 的索引 0 和 2?)并且过度截断(str_ireplace 调用在哪里)但是......我猜测你还没有完全理解 str_ireplace。
第一点是str_ireplace发挥不到位。它的返回值是更改后的字符串/字符串数组。
第二点是,当您有一系列搜索和替换时,PHP 将从每个数组中取出一个项目并将其应用到主题/主题数组,然后再转到每个数组中的下一个项目,然后应用对于同一主题。您可以在下面的示例中看到这一点,其中两个受试者都将“'”替换为“某物”,并且“同一件事只是以另一种方式”从未出现在结果中。
<代码>
$模式=数组();
$replacements = array();
$patterns[0] = "'";
$patterns[1] = '\'';
$replacements[0] = '东西';
$replacements[1] = '同样的事情,只是以另一种方式';
$subjects[0] = "我添加了单引号。";
$subjects[1] = "这也会有一个引号。";
$newSubjects = str_ireplace($patterns, $replacements, $subjects);
print_r( $newSubjects);
运行时给出
Array ( [0] => ISomethingve 包含单引号。 [1] => ThisSomethingll 也有一个引号。)
It looks like your sample code has been over anonymised (indexes 0 & 2 for $replacements?) and over truncated (where is the str_ireplace call) however... I'll take a guess that you haven't fully understood str_ireplace.
The first point is that str_ireplace does not work in place. It's return value is the altered string/array of strings.
The second point is that, when you have an array of searches and replacements, PHP will work through taking one item from each array and applying it to the subject/array of subjects, before moving on to the next item from each array and then applying that to the same subject(s). You can see this in the example below where both subjects have had "'" replaced with "something" and "Same thing just in a other way" never makes an appearance in the results.
$patterns = array();
$replacements = array();
$patterns[0] = "'";
$patterns[1] = '\'';
$replacements[0] = 'Something';
$replacements[1] = 'Same thing just in a other way';
$subjects[0] = "I've included a single quote.";
$subjects[1] = "This'll also have a quote.";
$newSubjects = str_ireplace($patterns, $replacements, $subjects);
print_r($newSubjects);
When run this gives
Array ( [0] => ISomethingve included a single quote. [1] => ThisSomethingll also have a quote. )