![](/img/trans.png)
[英]Every time I do a regular expression splitting in PHP the first and last string in the array PHP returns appears empty
[英]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.