0

I got an php array like this:

array(3) {
   [0]=> string(12) "server[edit]" 
   [1]=> string(14) "server[create]" 
   [2]=> string(12) "user[delete]" 
}

I want to convert this to different arrays - for example an array named server with "edit" and "create" in it - and another array "user" with "delete".

Whats the right pattern for that ?

Thanks for any help!

4
  • 1
    Why do you think regex is the tool for this job? Commented Nov 25, 2014 at 0:29
  • was my first idea, so it's possible to filter "server" and the action "edit" or "create" (but tbh i don't know how to) - is there another solution ? Commented Nov 25, 2014 at 0:31
  • 1
    meta.stackexchange.com/questions/66377/what-is-the-xy-problem Commented Nov 25, 2014 at 0:32
  • Looks like ^(\w+)\[(\w+)\]$ would be a good fit. But splitting this to different top-level arrays seems like a bad idea to me. Commented Nov 25, 2014 at 0:36

1 Answer 1

2

Rather than trying a regex against the whole array, try matching against each individual value. Take a look at this as an example

$array = array(
        'server[edit]',
        'server[create]',
        'user[delete]',
        'dsadsa'
);

$newArray = array();

foreach($array as $value)
{
        preg_match("~^(\w+)\[(\w+)\]$~", $value, $matches);
        if(count($matches))
        {       
                $key = $matches[1];
                if(!isset($newArray[$key]))
                        $newArray[$key] = array();

                $newArray[$key][] = $matches[2];
        }
}

var_dump($newArray);
Sign up to request clarification or add additional context in comments.

5 Comments

Your ? only applies to \] and the backslash is misplaced. I think you meant to write ~^(\w+)(?:\[(\w+)\])?$~
@LucasTrzesniewski Yeah, you're right about the ? and the \. I didn't want the ?: though, because I want the second capture to be value I insert into the arrays. I think that's what OP was aiming for
That's why I suggested (?:...) instead of (...). But now I see you removed the ? altogether.
@LucasTrzesniewski Sorry, I might be a bit rusty on my regex, but doesn't ?: meant that the capture bracket won't be returned in $matches, so $matches[2] will return null or not be defined?
@Gareth no, it just doesn't count as a capture group, $matches[2] will still return the same thing. There would be no point in always returning null for a group.

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.