0

I want to get multi result from Regex, but its not correctly work.

Test string:

<div class="row-fluid pybar-row">
    <span class="pybar-label text-left">
        <span class="">Male</span>
    </span>
    <span class="pybar-bars">
    <div class="row-fluid">
        <span class="pybar-bar pybar-l" style="">
            <span class="pybar-bg">
                <span style="width:100%">&nbsp;</span>
            </span>
        </span>
        <span class="pybar-bar pybar-r">
            <span class="pybar-bg">
                <span style="width:78%;">&nbsp;</span>
            </span>
        </span>
    </div>
</div>

I want to get only number of style="width:X%"

I used this regex:

$re = "/<span class=\"pybar-bg\">.*?width:(.*?)%/s";

But its only return first number. I want all numbers in string and have this class.

serenesat
  • 4,611
  • 10
  • 37
  • 53

2 Answers2

4

Your regular expression works correct. Use preg_match_all to extract all matches:

$s = <<<HTML
<div class="row-fluid pybar-row">
    <span class="pybar-label text-left">
        <span class="">Male</span>
    </span>
    <span class="pybar-bars">
    <div class="row-fluid">
        <span class="pybar-bar pybar-l" style="">
            <span class="pybar-bg">
                <span style="width:100%">&nbsp;</span>
            </span>
        </span>
        <span class="pybar-bar pybar-r">
            <span class="pybar-bg">
                <span style="width:78%;">&nbsp;</span>
            </span>
        </span>
    </div>
</div>
HTML;


$re = "/<span class=\"pybar-bg\">.*?width:(.*?)%/s";
if( preg_match_all( $re, $s, $matches ) ) {
    var_dump( $matches[1] );
}

This will output this:

array(2) {
  [0] =>
  string(3) "100"
  [1] =>
  string(2) "78"
}
Nicolai
  • 5,489
  • 1
  • 24
  • 31
1

Your regex is returning on first match. To match all values use g modifier (global match).

$re = "/<span class=\"pybar-bg\">.*?width:(.*?)%/sg";

Will return:

100
78

see demo

serenesat
  • 4,611
  • 10
  • 37
  • 53
  • That's not the right answer for THIS question: it's tagged `php` where no "g" modifier exists. Instead `preg_match_all()` must be used, as @Nicolai's answer said. – cFreed Jun 13 '15 at 14:12