1

Just wondering if you can help me out a bit with a little task I'm trying to do in php.

I have text that looks something like this in a file:

    (random html)
    ...
    <OPTION VALUE="195" SELECTED>Physical Chem  
    <OPTION VALUE="239">Physical Chem Lab II  
    <OPTION VALUE="555">Physical Chem for Engineers            
    ...
    (random html)

I want to return the # value of the option values ignoring everything else. For example, in the above case I would want 195, 239 & 555 returned, nothing else like "Option Value=".

I am having trouble doing this in PHP. So far I have this:

preg_match("/OPTION VALUE=\"([0-9]*)/", $data, $matches);
        print_r($matches);  

With the return value of this:

Array ( [0] => OPTION VALUE="195[1] => 195) Array ( [0] => OPTION VALUE="195[1] => 195)

How can I return the all the #'s?

I'm a newbie at pattern matching and tutorials I've read haven't helped much, so thanks a ton!

4 Answers 4

3

preg_match will return an array containing only the first match. The first index of the array wil return a match for the full regular expression, the second one matches the capture group in the parentheses, try the following to get a concept of how this works:

preg_match("/(OPTION) VALUE=\"([0-9]*)/", $data, $matches);
    print_r($matches);

You will see that it outputs the following:

Array
(
    [0] => OPTION VALUE="195
    [1] => OPTION
    [2] => 195
)

Array[0] contains data of the full match, array [1] contains data from the first capture group (OPTION) and array[2] contains data from the second capture group ([0-9]*).

In order to match more than one occurrence, you need to use the preg_match_all function. If we apply this to your original code like so:

preg_match_all("/OPTION VALUE=\"([0-9]*)/", $data, $matches);
    print_r($matches);

We get:

Array
(
    [0] => Array
        (
            [0] => OPTION VALUE="195
            [1] => OPTION VALUE="239
            [2] => OPTION VALUE="555
        )

    [1] => Array
        (
            [0] => 195
            [1] => 239
            [2] => 555
        )

)

I hope this makes things clear!

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

Comments

2

I think you've done it right. PHP returns the full match in [0], and then the captured groups (parenthases) as the others.

Check this out: http://xrg.es/#15m7krv

Comments

1

Try this:

preg_match_all('/OPTION VALUE=\"([0-9])+\"/', $data, $matches);

Edit

Misunderstood your question. Changed to preg_match_all()

Comments

1

Try using preg_match_all()

http://php.net/manual/en/function.preg-match-all.php

Comments

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.