gpt4 book ai didi

php - preg_replace 特殊字符上的错误

转载 作者:行者123 更新时间:2023-11-29 22:02:40 24 4
gpt4 key购买 nike

我想更改以下内容:
% =>\%
_ =>\_
\  =>\\

例如:

1. ali% sdn bhd -> ali\% sdn bhd
2. ali_ sdn bhd -> ali\_ sdn bhd
3. ali\ sdn bhd -> ali\\ sdn bhd

这是编写的代码:

<?php
$special_characters = array("%","_","\\");
$replace_special_characters = array("\\%","\\_","\\\\\\\\");

foreach($special_characters as $value)
{
if(strpos($companyname, $value) !== FALSE)
{
$companyname = preg_replace('/'.$value.'/', $replace_special_characters, $companyname); //ERROR HERE
}
}
?>

但是,从上面的输出中,我收到此错误:

Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array ...

我哪部分写错了?我该如何修改?

最佳答案

问题是您无法使用 preg_replace 将字符串替换为数组

您必须获取元素在数组中的位置,然后使用此位置进行替换:

<?php
$special_characters = array("%","_","\\");
$replace_special_characters = array("\\%","\\_","\\\\\\\\");

$i = 0; //set the original position
foreach($special_characters as $value)
{
if(strpos($companyname, $value) !== FALSE)
{
echo '/'.$value.'/';
$companyname = preg_replace('/'.$value.'/', $replace_special_characters[$i], $companyname); //Here you get replacement using the current position, so a string is set as replacement, not an array
}
$i++;//after each value, you increment the position
}
?>

我不确定这段代码是否有效,但它向您展示了需要实现的逻辑。

关于php - preg_replace 特殊字符上的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32473559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com