tags:

views:

90

answers:

8

In PHP

$regex = '/ ([$]) *(\d+(:?.\d+)?)/';
preg_match($regex, $str, $matches);

print_r($matches[2]);

This regex gives me the first occurence of a number that follows the first $ sign in a web page.

Now I want a regex that would give me the number after the second $ sign and maybe the third too.

+3  A: 

What you are looking for is the preg_match_all function.

preg_match_all('/([$])*(\d+(:?.\d+)?)/', $str, $result, [flags]);

$result contains all matches in an array in the order specified by flags.

slosd
A: 

preg_match only matches the first occurance of the regex, if you use preg_match_all, you'll get the array which you're after.

slightlymore
A: 

preg_match_all('/([$])*(\d+(:?.\d+)?)/', $str, $result, [flags]);

ok, what do I write after to print the result for second or third occorance?

and also I get an error: Parse error: syntax error, unexpected '['

it reffers to the [flags]

A: 

Second result should be $result[1], third $result[2] and so on.

Edit*

You don't want to actually use [flags], but one of the "flags" found here.

You probably want something along the lines of:

<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[3] . "\n";
    echo "part 3: " . $val[4] . "\n\n";
}
?>
Magic Hat
A: 

I am just getting the error :

Parse error: syntax error, unexpected '['

(where [flags] is written)

A: 

I tried

preg_match_all('/([$])*(\d+(:?.\d+)?)/', $str, $result, PREG_SET_ORDER);
foreach ($matches as $val) {
    echo "matched: " . $val[0] . "</br>";
    echo "part 1: " . $val[1] . "</br>";
    echo "part 2: " . $val[3] . "</br>";
    echo "part 3: " . $val[4] . "</br>";
}

it prints

matched: $ 218 part 1: $ part 2: part 3: matched: $ 218 part 1: $ part 2: part 3: matched: $ 224 part 1: $ part 2: part 3: matched: $ 224 part 1: $ part 2: part 3: matched: $ 225 part 1: $ part 2: part 3: matched: $ 225 part 1: $ part 2: part 3:

i just want the number how do i put each number in a different variable

A: 

ok i am trying to put

    if(i==3)
{$second=$val[2] ; }
$i++;

in the foreach loop but it just gives me the last value

btw thanks your answers were very good

A: 

ok it works! thanks! just had a syntax