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

时间:2017-09-11 02:50:56

标签: php regex codeigniter

我有一个文本文件,想要使用正则表达式将文本拆分为数组。但我是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"
...

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

2 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:1)

这看起来像一个奇怪的格式,所以我可能会错过一些东西,但这应该有效:

([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);

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

Demo