解析文本并从每行两个子字符串填充关联数组
给定一大串文本,我想搜索以下模式:
@key: value
所以一个例子是:
some crazy text
more nonesense
@first: first-value;
yet even more non-sense
@second: second-value;
finally more non-sense
输出应该是:
array("first" => "first-value", "second" => "second-value");
Given a large string of text, I want to search for the following patterns:
@key: value
So an example is:
some crazy text
more nonesense
@first: first-value;
yet even more non-sense
@second: second-value;
finally more non-sense
The output should be:
array("first" => "first-value", "second" => "second-value");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
链接http://ideone.com/fki3U
Link http://ideone.com/fki3U
在 PHP 5.3 中测试:
背后的原因是:
该密钥的其他数据。捕获组是正则表达式的部分
在左右香蕉里面,即(...)。
$actualMatches
只是根据 preg_match_all 返回一个事实进行调整包含所有匹配项的额外元素。
演示。
Tested in PHP 5.3:
The reasoning behind this is this:
other the data for that key. The capture groups are the portions of the regex
inside left and right bananas, i.e., (...).
$actualMatches
just adjusts for the fact that preg_match_all returns anextra element containing all matches lumped together.
Demo.
匹配以
@
开头并以;
结尾的整个限定行。捕获不包含任何冒号的子字符串作为第一组,并捕获冒号后面的空格与行尾分号之间的子字符串。
通过使用第二个捕获组中的任意字符点,子字符串可以包含分号,而不会损坏任何提取的数据。
调用 array_combine() 来形成两个捕获组之间的键值关系。
代码:(演示)
输出:
Match whole qualifying lines starting with
@
and ending with;
.Capture the substring that does not contain any colons as the first group and capture the substring between the space after the colon and the semicolon at the end of the line.
By using the any character dot in the second capture group, the substring may contain a semicolon without damaging any extracted data.
Call
array_combine()
to form key-value relationships between the two capture groups.Code: (Demo)
Output:
您可以尝试逐行循环字符串(分解和 foreach),并检查该行是否以 @(子字符串)开头,如果有,则通过 : 分解该行。
http://php.net/manual/en/function.explode.php
http://nl.php.net/manual/en/control-structs .foreach.php
http://nl.php.net/manual/en/function.substr.php
You can try looping the string line by line (explode and foreach) and check if the line starts with an @ (substr) if it has, explode the line by :.
http://php.net/manual/en/function.explode.php
http://nl.php.net/manual/en/control-structures.foreach.php
http://nl.php.net/manual/en/function.substr.php
根据您的输入字符串的样子,您可能可以简单地使用
parse_ini_string
,或者对字符串进行一些小的更改,然后使用该函数。Depending on what your input string looks like, you might be able to simply use
parse_ini_string
, or make some small changes to the string then use the function.