1

I have a string that holds the property and key values to accessing a value on an object..

For Example, the string is "property_name[key1][key2][key3]", which relates to $obj->property_name[key1][key2][key3]

I've been trying to parse the string with a regular expression, but all of my attempts have ben in vain.

So far, my regular expression looks like this, but it won't get key2. ^(\w+)\[([^\]]+)\](?:(\[([^\]]+)\])+)

Am I on the right track or is there a better way to do this that I should try?

Thanks.

2
  • 2
    You're probably doing something wrong. Where do you get these strings from? Maybe you can save them as JSON instead? Commented Mar 6, 2013 at 8:11
  • They're the names of fields in a form that have been changed. I'm trying to update a few fields in multiple records when a user changes a value from my form. I'm using javascript to save the field names to a hidden element to get these. Commented Mar 6, 2013 at 8:15

2 Answers 2

1

The regular expression could look like this:

^(\w+)(?:\[(\w+)\])+

Then your matches will contain the property name and the array keys. If the number of keys varies, use this to get the actual value: Using a path to an array item

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

1 Comment

I ended up using a combination of the link here and this regular expression @^(\w+)(\[([^]].*)\])@
0

You should use AJAX instead and send a useful array with objects inside to the server that you can parse with PHP.

var changed_values = [
                      {
                       'part_of_form': 'XX',
                       'field': 2,
                       'subfield': 3
                      },
        .......
                     ]

Then in PHP you can loop over it:

foreach($_POST['changed_values'] as $changed_value) {
  ........
}

1 Comment

This is exactly what I am trying to do.

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.