简体   繁体   中英

Get associative array using preg_split

I have 2 issues with my below regex:

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).

2) Is it possible to get associative array from this? I mean I want output in the form of $output = array("title" => "Book1", "writer" => "writer1", "isbn" => "1234") in this format.

$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):

$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.

Note that you can filter numeric keys since PHP 5.6 like this (not tested):

$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:

$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). Be careful, as it use JSON, it may have some problem with " or unexpected string not in [tag]string[/tag] pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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