Home > Mobile >  Get everything after specific word and before specific word in PHP
Get everything after specific word and before specific word in PHP

Time:07-31

Take a look this string: (parent)item category(child)master data(name)category

by the way, that string is dynamic, and I want word inside () as array key and everything after () is that key value before next ()

how can I get the array result from the string above to this: ["parent" => "item category", "child" => "master data", "name" => "category"]?

CodePudding user response:

This probably is what you are looking for:

<?php
$input = "(parent)item category(child)master data(name)category";
preg_match_all('/\(([^()] )\)([^()] )/', $input, $matches);
$output = array_combine($matches[1], $matches[2]);
print_r($output);

The output obviously is:

Array
(
    [parent] => item category
    [child] => master data
    [name] => category
)

The approach uses a "regular expression" matching all occurrences of a pattern in the input string. All that is left is to combine the matched tokens which is done by the array_combine(...) call.

Note that such an approach works, but is very limited. It fails with more complex input structure due to the fact that pattern matching based on regular expressions is limited itself. In such cases you'd either have to implement a real language parser (or use a compiler-compiler like yacc or bison to do that for you). Or you simplify your input data structure which usually is more promising ;-)

CodePudding user response:

you can use explode to get an array based on the selected word

<?php
$str = "(parent)item category(child)master data(name)category";
$list = explode("(", $str);
$x = [];
foreach($list as $item){
    if($item != null) {
        $i = explode(")",$item);
        $x[$i[0]] = $i[1];
    }
}
print_r($x);
  • Related