Jump to content

Turning string into array indexer


Nolongerused3921

Recommended Posts

I'm having a bit of a problem - I need to access an array entry (I.e., $array['key']['key2']) with a plain text string ($string = "[key][key2]"), but I'm not sure how to go about doing this... I've attempted to get the keys via regex, but that's not going so well and I'm going a bit insane, so I thought I'd get some help here.

 

The regex, to give you an idea what I'm trying to do (I'd prefer not to use regex, if anyone can think of another way) :

preg_match("/^([a-zA-Z0-9]+)(\[([a-zA-Z0-9]+)\])*/", $inputName, $sdf);

 

Returns:

cat[goes][meow]

0: Array

(

    [0] => cat[goes][meow]

    [1] => cat

    [2] => [meow]

    [3] => meow

)

 

I've tried several variations, but they always result in only one key being matched and returned.

Link to comment
Share on other sites

Here's one way of doing it:

<?php
$str = '[testkey1][testkey2]';
list($dk1,$dk2) = explode('][',$str);
list(,$key1) = explode('[',$dk1);
list($key2) = explode(']',$dk2);
echo 'key1 = ' . $key1 . "<br>\n";
echo 'key2 = ' . $key2 . "<br>\n";
?>

 

Ken

Link to comment
Share on other sites

Thanks for the quick reply, however I should have mentioned I had tried that, deciding not to use it due to issues with the speed of it.

 

Sadly speed is broken down to: Functionless method (God I hope there's one)->Regex->sscanf->explode... The function will be called a lot, so I really wanna try to find something that's as faster than regex, but failing that - regex.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.