Php preg_替换特殊字符上的错误

Php preg_替换特殊字符上的错误,php,mysql,preg-replace,Php,Mysql,Preg Replace,我想更改以下内容,如下所示: % => \% _ => \_ \=>\\ 例如: 下面是编写的代码: <?php $special_characters = array("%","_","\\"); $replace_special_characters = array("\\%","\\_","\\\\\\\\"); foreach($special_characters as $value) { if(strpos($companyname, $value) !

我想更改以下内容,如下所示: % => \% _ => \_ \=>\\

例如:

下面是编写的代码:

<?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
        }   
}
?>

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

问题是不能使用preg\u 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
}
?>
我不确定这段代码是否有效,但它向您展示了需要实现的逻辑。

为什么不使用

输出:

从文件中:

注意,更换订单有问题

因为str_replace从左到右替换,所以它可能会替换 以前在执行多个替换时插入的值。另见 本文档中的示例


这无法工作,同一行上的另一个错误:preg_replace:找不到结束分隔符“/”…正如我所说的,这不保证工作正常,这里的目标是让您了解错误是什么。我认为您应该在preg_replace之前添加一些调试,以了解您当前正在寻找的$value。我更新了这个示例,向您展示了我是如何遗漏了一些显而易见的东西,但str_replace函数是否已经涵盖了这一点?
Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array ...
<?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
}
?>
$string = 'ali% sdn bhd ali_ sdn bhd  ali\ sdn bhd';
$res = str_replace(array("\\","%","_"), array("\\\\","\\%","\\_"), $string);
echo $res,"\n";
ali\% sdn bhd ali\_ sdn bhd  ali\\ sdn bhd