Analysing a string, probably using a regex

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pinhead
Forum Newbie
Posts: 1
Joined: Sun Apr 06, 2008 6:12 am

Analysing a string, probably using a regex

Post by pinhead »

Hi everyone
I have a string, that I want to analyse and load into an array. The string looks something like this:

Code: Select all

"<something>[blah][dkl][ilow]<somestring>[fdskl][iloveu]<anotherone>[dfsk]"
And I want the result looking something like this:

Code: Select all

 Array
(
    ['something'] => Array
        (
            [0] => blah
            [1] => dkl
            [2] => ilow
        )
 
    ['somestring'] => Array
        (
            [0] => fdskl
            [1] => iloveu
        )
 
    ['anotherone'] => Array
        (
            [0] => dfsk
        )
 
)
The result does not have to be exactly like this, I just need to see the structure of the original string. Also note that the input has an undefinded number of entries, so the result may be an array with three items like in the example above, but may also contain several hundered items..

I know that this can be done some loops in combination with strpos, but I don't like this approach. Does anyone have a cool idea how to do this job in a smart, and primarily fast way? I guess some regex magic could be used, but I don't know how at the moment.
aCa
Forum Newbie
Posts: 11
Joined: Sun Apr 06, 2008 3:43 pm

Re: Analysing a string, probably using a regex

Post by aCa »

Do you need to know wich elements are grouped together? Or is it enough that you get blah, dkl etc listed after each other in a big array? If that is enough you can use the following pattern with ungreedy.

Pattern: \[(.+)\]

Code: Select all

preg_match_all('/\[(.+)\]/U', '<something>[blah][dkl][ilow]<somestring>[fdskl][iloveu]<anotherone>[dfsk]', $result);
Or pattern: (\[[^\]]+\]) withour greedy.

Code: Select all

preg_match_all('/(\[[^\]]+\])/', '<something>[blah][dkl][ilow] <somestring>[fdskl][iloveu]<anotherone>[dfsk]', $result);
you can test it on my regex tool at http://regex.larsolavtorvik.com/ too see if that meets you needs. If you need to have them grouped you can use a loop. For instance using this first

Pattern: (\[[^\]]+\])+

Code: Select all

preg_match_all('/(\[[^\]]+\])+/', '<something>[blah][dkl][ilow] <somestring>[fdskl][iloveu]<anotherone>[dfsk]', $result);
And then looping $result[0] with one of the two first patterns I sugested.

Hope this makes sense... try and test a bit and see if you can use any the patterns :-)

There might be a way to do this without the looping, just can't think one one at the moment
Post Reply