Jump to content

parsing text


xrado

Recommended Posts

i would like to parse string:
apple(3),banana(10),orange(aaa)

and get out the fruit name and what ever is between ()

[code]Array
(
    [0] => Array
        (
            [0] => apple
            [1] => 3
        )
    [1] => Array
        (
            [0] => banana
            [1] => 4
        )
    [2] => Array
        (
            [0] => orange
            [1] => aaa
        )
)[/code]

i would also like to still get the name if () is missing ..like this [move][move][/move][/move]

[code]    [2] => Array
        (
            [0] => orange
            [1] =>
        )[/code]

...this is what i achomplished till now with

[code]$aa = "apple(3),banana(10),orange(aaa)";
preg_match_all("/([a-zA-Z0-9 ]*)(\(?([a-zA-Z0-9]*)\)?)/", $aa, $matches, PREG_SET_ORDER);
print_r($matches);[/code]

[code]Array
(
    [0] => Array
        (
            [0] => apple(3)
            [1] => apple
            [2] => (3)
            [3] => 3
        )

    [1] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
        )

    [2] => Array
        (
            [0] => banana(10)
            [1] => banana
            [2] => (10)
            [3] => 10
        )

    [3] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
        )

    [4] => Array
        (
            [0] => orange(aaa)
            [1] => orange
            [2] => (aaa)
            [3] => aaa
        )

    [5] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
        )

)[/code]

if i get four dimensional resoult its ok..but i dont want empty result
Link to comment
Share on other sites

Well, if you want to catch everything but commas you define a class of chars that has only the comma within and deny it [^,]. You could use something similar to match everything (white spaces included) inside the brakets [^)] and outside [^,)]. Something like this it'd have to work:
[code]

$aa = "apple(3),ban ana ,ora ng e( a a a),pineapple";
preg_match_all( '/([^(,]+)\s*(?:\(([^)]*)\))?/',$aa,$mth,PREG_SET_ORDER ) ;

[/code]
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.