3

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|
4
  • 1
    php.net/manual/en/function.preg-quote.php Commented Feb 5, 2018 at 8:03
  • 1
    You did not research this, as any reasonable search on the internet would have pointed you to the right method. Commented Feb 5, 2018 at 8:06
  • 1
    There is another way too "\Q" . implode("\E|\Q", $arr) . "\E" Commented Feb 5, 2018 at 8:16
  • See stackoverflow.com/questions/1531456/… Commented Feb 5, 2018 at 8:17

1 Answer 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|
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.