views:

14

answers:

1

HI all i have a string

<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>

i need to get 10000 as answer .. how i use preg_match ??? Note: this is implortant that the multiple occurance of match

Thanks in advance

+1  A: 

At least for this particular case, you could use '/\(\d+\-\d+ of (\d+)\)/' as the pattern.

It matches strings like this ({one-or-more-digits}-{one-or-more-digits} of {one-or-more-digits}) and captures the last {one-or-more-digits} into a group ({}s added just for clarity's sake here..).

$str = '<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>';
$matches = array();
if (preg_match('/\(\d+\-\d+ of (\d+)\)/', $str, $matches))
{
    print_r($matches);
}

prints:

Array
(
    [0] => (1-20 of 10000)
    [1] => 10000
)

So, the 10000 you are looking for would be accessible at $matches[1].


Edit after your comment: If you have multiple occurrences of ({one-or-more-digits}-{one-or-more-digits} of {one-or-more-digits}), you can use preg_match_all to catch them all. I'm not sure how useful the numbers themselves are without the context in which they occur, but here's how you could do it:

$str = '<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>';
$str .= "\n$str\n";
echo $str;
$matches = array();
preg_match_all('/\(\d+\-\d+ of (\d+)\)/', $str, $matches);
print_r($matches);

prints:

<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
Array
(
    [0] => Array
        (
            [0] => (1-20 of 10000)
            [1] => (1-20 of 10000)
        )

    [1] => Array
        (
            [0] => 10000
            [1] => 10000
        )

)

Again, what you're looking for would be in $matches[1], only this time it'll be an array containing 1 or more of the actual values.

Lauri Lehtinen
@Lauri Lehtinen: What does it do `(\d+)` without braces?
Sarfraz
@Lauri Lehtinen ..its work fine if the string contain only one (1-20 of 10000) ... but in my case there is a chance of multiple occurance
Nisanth
Would you mind editing your question to reflect the real situation?
Lauri Lehtinen
@sAc I'm not sure I understand your question?
Lauri Lehtinen
@Lauri Lehtinen : Thank u very much i got the answer :)
Nisanth