PHP preg_split ignores escape sequence

How can I split the string one by one, but ignore the escaped character? Here is my example, I have a line: -

\ntest\rtest\n 

I want it to be like this: -

 Array ( [0] => \n [1] => t [2] => e [3] => s [4] => t [5] => \r [6] => t [7] => e [8] => s [9] => t [10] => \n ) 

Someone said to use preg_split, but I know little about regex.

+4
source share
4 answers

Backslashes need escaping in RegEx.
When you reference one valid backslash, you will need a series of three \\\

RegEx Compliance

 preg_match_all("/\\\?[^\\\]/", $str, $matches); 

Live demo code: http://codepad.viper-7.com/FLjH9A

RegEx split - for educational purposes only, as a match in this case is more suitable

 $matches=preg_split("/(?<=\\\[^\\\])(?!$)|(?<=[^\\\])(?!$)/", $str); 

Real-time demo code: http://codepad.viper-7.com/yrbtMV

+3
source

You can remove the escaped characters first and then apply str_split() :

 $str = "\ntest\rtest\n"; print_r(str_split(strtr($str, array( '\r' => '', '\n' => '', )))); 
+2
source

if you want to get an array, you can read the string with char one by one. regardless of regular expression.

+1
source

If you want to match every single character (optionally preceding \ ), you can use:

 $str = '\ntest\rtest\n'; preg_match_all('/\\\?[a-zA-Z]/', $str, $matches); 

To return an array with single and escaped character sequences.

0
source

Source: https://habr.com/ru/post/1479867/


All Articles