我解析文本,但我不能獲得時的空間缺少件(這是OK)
編輯的字符串的數組:我已添加冒號到自由文本。
編輯:好吧,這是一個可以寫入鍵值對的任意文本格式。丟棄元素[0],數組中的其餘元素產生一系列鍵值。它接受多行值。拆分使用正則表達式來獲得關鍵值對
這是測試用例文本:
:part1 only one \s removed:OK
:part2 :text :with
new lines
on it
:noSpaceAfterThis
:thisShoudBeAStandAlongText but: here there are more text
:part4 :even more text
這就是我想要的:
Array
(
[0] =>
[1] => part1
[2] => only one \s removed:OK
[3] => part2
[4] => :text :with
new lines
on it
[5] => noSpaceAfterThis
[6] =>
[7] => thisShoudBeAStandAlongText
[8] => but: here there are more text
[9] => part4
[10] => :even more text
)
這就是我得到:
Array
(
[0] =>
[1] => part1
[2] => only one \s removed:OK
[3] => part2
[4] => :text :with
new lines
on it
[5] => noSpaceAfterThis
[6] => :thisShoudBeAStandAlongText but: here there are more text
[7] => part4
[8] => :even more text
)
這是我的測試代碼:
<?php
$text = '
:part1 only one \s removed:OK
:part2 :text :with
new lines
on it
:noSpaceAfterThis
:thisShoudBeAStandAlongText but: here there are more text
:part4 :even more text';
echo '<pre>';
// my effort so far:
$ret = preg_split('|\r?\n:([\w\d]+)(?:\r?\s)?|i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($ret);
// nor this one:
$ret = preg_split('|\r?\n:([\w\d]+)\r?\s?|i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($ret);
// for debuging, an extra capturing group
$ret = preg_split('|\r?\n:([\w\d]+)(\r?\s)?|i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
var_dump($ret);
這將幫助別人知道規則是什麼,即爲什麼要匹配你想要的方式? :) –
@傑克你是正確的,我希望你同意我所做的編輯。 –