Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get everything after specific word and before specific word in PHP

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"]?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 😉

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading