How can I split string one by one but ignoring escaped character ? Here my example, I have string :-
如何逐个拆分字符串但忽略转义字符?这是我的例子,我有字符串: -
\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 use preg_split, but i don't know much about regex.
有人说使用preg_split,但我不太了解正则表达式。
4 个解决方案
#1
3
Backslashes need escaping in RegEx.
When referencing one actual backslash you'll need a series of three \\\
反斜杠需要在RegEx中转义。当引用一个实际反斜杠时,你需要一系列三个\\\
RegEx match
preg_match_all("/\\\?[^\\\]/", $str, $matches);
Live demo code: http://codepad.viper-7.com/FLjH9A
现场演示代码:http://codepad.viper-7.com/FLjH9A
RegEx split - just for educational purposes, as match is more appropriate in this case
RegEx拆分 - 仅用于教育目的,因为在这种情况下匹配更合适
$matches=preg_split("/(?<=\\\[^\\\])(?!$)|(?<=[^\\\])(?!$)/", $str);
Live demo code: http://codepad.viper-7.com/yrbtMV
现场演示代码:http://codepad.viper-7.com/yrbtMV
#2
2
You can remove the escaped characters of choice first and then apply str_split()
:
您可以先删除所选的转义字符,然后应用str_split():
$str = "\ntest\rtest\n";
print_r(str_split(strtr($str, array(
'\r' => '',
'\n' => '',
))));
#3
1
if you only want to get the array, you can read the string with char one by one. no matter about regex.
如果你只想获取数组,你可以逐个读取字符串。无论是关于正则表达式。
#4
0
If you want to match each single character (optionally preceded by a \
), you can use:
如果要匹配每个单个字符(可选地以\开头),您可以使用:
$str = '\ntest\rtest\n';
preg_match_all('/\\\?[a-zA-Z]/', $str, $matches);
Which would return an array with both the single and escaped character sequences.
哪个会返回包含单个和转义字符序列的数组。
#1
3
Backslashes need escaping in RegEx.
When referencing one actual backslash you'll need a series of three \\\
反斜杠需要在RegEx中转义。当引用一个实际反斜杠时,你需要一系列三个\\\
RegEx match
preg_match_all("/\\\?[^\\\]/", $str, $matches);
Live demo code: http://codepad.viper-7.com/FLjH9A
现场演示代码:http://codepad.viper-7.com/FLjH9A
RegEx split - just for educational purposes, as match is more appropriate in this case
RegEx拆分 - 仅用于教育目的,因为在这种情况下匹配更合适
$matches=preg_split("/(?<=\\\[^\\\])(?!$)|(?<=[^\\\])(?!$)/", $str);
Live demo code: http://codepad.viper-7.com/yrbtMV
现场演示代码:http://codepad.viper-7.com/yrbtMV
#2
2
You can remove the escaped characters of choice first and then apply str_split()
:
您可以先删除所选的转义字符,然后应用str_split():
$str = "\ntest\rtest\n";
print_r(str_split(strtr($str, array(
'\r' => '',
'\n' => '',
))));
#3
1
if you only want to get the array, you can read the string with char one by one. no matter about regex.
如果你只想获取数组,你可以逐个读取字符串。无论是关于正则表达式。
#4
0
If you want to match each single character (optionally preceded by a \
), you can use:
如果要匹配每个单个字符(可选地以\开头),您可以使用:
$str = '\ntest\rtest\n';
preg_match_all('/\\\?[a-zA-Z]/', $str, $matches);
Which would return an array with both the single and escaped character sequences.
哪个会返回包含单个和转义字符序列的数组。