Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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|
like image 235
DMP Avatar asked Jan 01 '26 09:01

DMP


1 Answers

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|
like image 199
Syscall Avatar answered Jan 02 '26 22:01

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!