简体   繁体   中英

How to escape regex special characters from array using php to use in javascript

I have an array that also contains regex special characters in its some values, I want to implode() it so that special characters in its some values escape using preg_quote()

Here is what I tried

$arr = array("+1", "1+4"); 
echo implode("|", $arr);

I want escaped output like this

\+1|1\+4|

You could use array_map() with preg_quote() like this :

$arr = array("+1", "1+4"); 
echo implode("|", array_map('preg_quote', $arr));

Outputs :

\+1|1\+4

To get the final pipe :

$arr = array("+1", "1+4" , ""); 
echo implode("|", array_map('preg_quote', $arr)) ;
// Or
$arr = array("+1", "1+4"); 
echo implode("|", array_map('preg_quote', $arr)) . "|" ;

Outputs :

\+1|1\+4|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM