[英]PHP - Split string into array
我有一個看起來像這樣的php字符串...
[line1]this is some test text[/line1][line2]This is line 2 text[/line2][line3]This is line 3 text[/line3]
我正在嘗試采用這種方法,並創建一個看起來像這樣的數組。
array(
"line1"=>"this is some test text",
"line2"=>"This is line 2 text",
"line3"=>"This is line 3 text"
)
該字符串是動態創建的,因此可以包含第1行-第99行,依此類推。
做到這一點並使其可擴展的最佳方法是什么? 有人能給我指出一個例子嗎?
就正則表達式而言,這可能是對匹配模式的合理折衷。
注意: 這不會處理嵌套/遞歸。
\\[([^\\]]+)\\](.*?)\\[/\\g{1}\\]
用法:
preg_match_all( '%\[([^\]]+)\](.*?)\[/\g{1}\]%', $subject, $matches, PREG_SET_ORDER );
var_dump( $matches );
Match the character “[” literally «\[»
Match the regex below and capture its match into backreference number 1 «([^\]]+)»
Match any character that is NOT a “]” «[^\]]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “]” literally «\]»
Match the regex below and capture its match into backreference number 2 «(.*)»
Match any single character that is NOT a line break character (line feed) «.*»
Between zero and unlimited times, as many times as possible, giving back as needed (lazy) «*»
Match the character “[” literally «\[»
Match the character “/” literally «/»
Match the same text that was most recently matched by capturing group number 1 (case sensitive; fail if the group did not participate in the match so far) «\g{1}»
Match the character “]” literally «\]»
您可以使用explode
采取這種方法(通過多次拆分輸入字符串)來隔離相關數據: line-id和line-text :
$text = "[line1]this is some test text[/line1][line2]This is line 2 text[/line2][line3]This is line 3 text[/line3]";
$text = explode( '][line', ']'.$text.'[line');
// you'll get a spurious item at index 0 and at the end, they'll be skipped
$n = count( $text );
$output = array();
for( $i = 1; $i < $n - 1; $i++ )
{
$line = explode( ']', $text[ $i] );
$id = 'line' . $line[ 0 ];
$line = explode( '[', $line[ 1 ] );
$value = $line[ 0 ];
$output[ $id ] = $value;
}
var_export( $output );
echo "\n";
你得到:
array (
'line1' => 'this is some test text',
'line2' => 'This is line 2 text',
'line3' => 'This is line 3 text',
)
注意:
可以容忍並正確處理空的“行”
line
文本中的方形制動器會破壞代碼並擰緊所有內容。
輸入格式必須嚴格按照以下格式
[line
n [line
]
文本 [/line
n [/line
]
....
如果您還有其他要求,可以調整代碼。
我認為這可能是一個很好的起點。
注意(再次):
這是一個可行的解決方案(鑒於上述限制)。
另一種方法是使用正則表達式和preg_match_all()
使用捕獲組來檢索行ID和行文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.