[英]PHP codeigniter splitting string to array by regular expression
I have a text file and want to split the text into array using regular expression. 我有一个文本文件,想使用正则表达式将文本拆分为数组。 But I am new to regex and don't know how to use it.
但是我对regex并不陌生,不知道如何使用它。 The text file format is basically like this:
文本文件格式基本上是这样的:
0,"20"1,"100000050"25,"100000050"19,""11,"Masuda"12,"Jin"
I want to split them like:
0: 0,"20"
1: 1,"100000050"
2: 25,"100000050"
...
Please help! 请帮忙! Any answer would be appreciated!
任何答案将不胜感激!
Use the preg_split() function. 使用preg_split()函数。 It operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
它的操作与split()完全一样,只是正则表达式被接受为pattern的输入参数。
Using PREG_SPLIT_DELIM_CAPTURE
returns the parenthesized expression in the delimiter pattern. 使用
PREG_SPLIT_DELIM_CAPTURE
以定界符模式返回带括号的表达式。
preg_split(
'/([\d]+,\"[0-9a-zA-Z]+\")/',
$str,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
/([\\d]+,\\"[0-9a-zA-Z]+\\")/
is the regular expression. /([\\d]+,\\"[0-9a-zA-Z]+\\")/
是正则表达式。
/ = start or end of pattern string
[ ... ] = grouping of characters
\d - digits
+ = one or more of the preceeding character or group
, = the literal comma character
\" = the literal quote character
[0-9a-zA-Z] = numbers and letters
That seems like a weird formatting so I might miss something, but this should work: 这似乎是一种怪异的格式,所以我可能会错过一些东西,但这应该可行:
([0-9]+,\"([0-9a-z ]+)?\")
Details 细节
[0-9]+ match a digit one or more times (this seems to be an ID of sorts)
, match a literal comma
\"([0-9a-z ]+)?\" match an alphanumeric character or a space one or more times, optionally (you have an empty string), between quotes
i flag to make it case insensitive
Pair it with preg_match_all()
to get all the matches in an array: 将其与
preg_match_all()
配对以获取数组中的所有匹配项:
<?php
$string = '0,"20"1,"100000050"25,"100000050"19,""11,"Masuda"12,"Jin"';
preg_match_all("/([0-9]+,\"([0-9a-z]+)?\")/i", $string, $m);
var_dump($m);
The first array will have what you need. 第一个阵列将满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.