1

I have input string from users. this input from users are unpredictable. it's mean user can input any string as they like. I would like to filter the input that match following pattern and return it as an array

These following string pattern should works:

product=bag, product=tshirt, product=shoes

product=bag status=sold, product=jeans, product=shoes

product=all

I would like the output as array like below :

Array(
 [0] => Array
  (
    [product] => bag
    [status]  => sold
  )

 [1] => Array
  (
    [product] => jeans
  )

 [2] => Array
  (
    [product] => shoes
  )
)

I guess it can be achieved by use preg_match_all() beside explode. Anyone can give me example using preg_match_all ? or any other ways are ok for me as long as the best method.

$string = 'product=bag status=sold, product=tshirt, product=shoes';
$m = preg_match_all('/needregexrulehere/', $string, $matches);
3
  • @ethrbunny Sorry, but he's not using the e modifier :) Commented Mar 25, 2013 at 20:09
  • to clarify: this is should php function not command line, all params above is defined in variable. the point is I just split the array above as an array as output above. let me know if you need more clarify. thx Commented Mar 25, 2013 at 20:21
  • @ethrbunny try it yourself !!! Commented Mar 25, 2013 at 20:40

1 Answer 1

1

You don't need a regular expression for this, you can do something like this:

$return = array();
foreach( str_getcsv( $string) as $line) {
    parse_str( str_replace( ' ' , '&', $line), $temp);
    $return[] = $temp;
}

This will output:

Array
(
    [0] => Array
        (
            [product] => bag
            [status] => sold
        )

    [1] => Array
        (
            [product] => tshirt
        )

    [2] => Array
        (
            [product] => shoes
        )

)

I will leave error checking / input sanitation up to the OP.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Nice, and I was going to write a solution with explode() & preg_match() xD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.