preg_replace特殊字符的错误

时间:2015-09-09 07:35:48

标签: php mysql preg-replace

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

E.g:

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 ...

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

2 个答案:

答案 0 :(得分:0)

问题是您无法使用preg_replace用string替换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
}
?>

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

答案 1 :(得分:0)

为什么不使用str_replace

$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

来自文档:

  

小心更换订单问题

     

因为str_replace()从左到右替换,所以它可能会替换a   多次替换时先前插入的值。也可以看看   本文档中的示例。