简体   繁体   English

使用preg_split获取关联数组

[英]Get associative array using preg_split

I have 2 issues with my below regex: 我的下面的正则表达式有2个问题:

1) The output shows 2 extra (blank) element at the beginning and end (can't use PREG_SPLIT_NO_EMPTY as isbn can be empty). 1)输出在开头和结尾显示2个额外(空白)元素(不能使用PREG_SPLIT_NO_EMPTY,因为isbn可以为空)。

2) Is it possible to get associative array from this? 2)是否可以从中获取关联数组? I mean I want output in the form of $output = array("title" => "Book1", "writer" => "writer1", "isbn" => "1234") in this format. 我的意思是我希望以这种格式输出$ output = array(“title”=>“Book1”,“writer”=>“writer1”,“isbn”=>“1234”)的形式。

$val = "[title]Book1[/title][writer]Writer1[/writer][isbn]1234[/isbn]";
$pattern = '/\[title](.*?)\[\/title].*?\[writer](.*?)\[\/writer].*?\[isbn](.*?)\[\/isbn]/i';
$allparams = preg_split($pattern, $val, -1, PREG_SPLIT_DELIM_CAPTURE);

Output: 输出:

Array ( [0] => [1] => Book1 [2] => Writer1 [3] => 1234 [4] => )

preg_split isn't the way to go, use preg_match (or preg_match_all if your want several results from a single string): preg_split是不是要走的路,使用preg_match (或preg_match_all如果你想从一个字符串几个结果):

$pattern = '~
    \[title]  (?<title>  [^[]+ ) \[/title]  .*?
    \[writer] (?<writer> [^[]+ ) \[/writer] .*?
    \[isbn]   (?<isbn>   [^[]+ ) \[/isbn]
~sx';

if (preg_match($pattern, $yourtext, $m)) {
    echo 'title:  ' . $m['title']  . PHP_EOL
       . 'writer: ' . $m['writer'] . PHP_EOL
       . 'isbn:   ' . $m['isbn']   . PHP_EOL;
}

The s flag allows the dot to match newlines, and the x flag ignores whitespaces in the pattern. s标志允许点匹配换行符, x标志忽略模式中的空格。

Note that you can filter numeric keys since PHP 5.6 like this (not tested): 请注意,您可以像PHP 5.6一样过滤数字键(未经测试):

$result = array_filter($m, function ($k) { return !is_numeric($k); }, ARRAY_FILTER_USE_KEY);

If you don't have PHP >= 5.6, a simple foreach loop can do the job: 如果你没有PHP> = 5.6,一个简单的foreach循环可以完成这项工作:

$result = array();
foreach ($m as $k=>$v) {
    if (is_numeric($k) || empty($v)) continue;
    $result[$k] = $v;
}

something like that will do the trick, even if it's not the best way I think... 类似的东西会起作用,即使这不是我想的最好的方式......

$a = "/\[(.*)\](.*)\[\/.*\]/U";
$val = "[title]Book1[/title][writer]Writer1[/writer][isbn]1234[/isbn]";
$array = json_decode('{'.substr(preg_replace($a, ',"$1":"$2"', $val), 1).'}');

BTW, this one find every [TAG] and put it in the array (whenever how many tag you use). 顺便说一句,这个找到每个[TAG]并将其放入数组中(无论你使用多少个标签)。 Be careful, as it use JSON, it may have some problem with " or unexpected string not in [tag]string[/tag] pattern. 要小心,因为它使用JSON,它可能有一些问题"或意外的字符串不在[tag]string[/tag]模式中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM