繁体   English   中英

PHP Codeigniter通过正则表达式将字符串拆分为数组

[英]PHP codeigniter splitting string to array by regular expression

我有一个文本文件,想使用正则表达式将文本拆分为数组。 但是我对regex并不陌生,不知道如何使用它。 文本文件格式基本上是这样的:

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"
...

请帮忙! 任何答案将不胜感激!

使用preg_split()函数。 它的操作与split()完全一样,只是正则表达式被接受为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]+\\")/是正则表达式。

/ = 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

这似乎是一种怪异的格式,所以我可能会错过一些东西,但这应该可行:

([0-9]+,\"([0-9a-z ]+)?\")

细节

[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

将其与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);

第一个阵列将满足您的需求。

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM