Question

I had a string contains html tags, and I want to get the whole string between which contains the keyword "GB".

sometimes there are different class or style attributes in the <td>, and also there might have different capacity between tags, so I was thinking to find "GB" or "gb" and then get whole string between ">" and "<"... but just have no idea how...

example of my string as shown as below:

$str='<tr>
    <td class="table_title13_bg_gray_line" width="171" align="left">Capacity</td>
    <td class="table_line_x_h10" width="647" align="left">&nbsp;16GB/32GB/64GB/128GB</td>
</tr>';

From the string above, I would like to get the string "16GB/32GB/64GB/128GB" Can anyone please let me know what should I do?

EDIT: And says if there are some tags in "16GB/32GB/64GB/128GB",

ex. <td class="table_line_x_h10" width="647" align="left">&nbsp;16GB/<span style="color:red;">32GB</span>/64GB<br/>128GB</td>

it seems the pattern $pattern = "/<td ?.*>(.*?)<\/td>/"; wont't work, so what else can I do?

Was it helpful?

Solution

Just tried and solved the question on my own... answer here and hope it's useful for someone else.

$pattern = "/<td ?.*>(.*)<\/td>/";
preg_match_all($pattern, $str, $matches);
foreach( $matches[0] as $key=>$val){ 
    if(preg_match('/GB/i',$val)){
        echo $val;
    }
}
//output: 16GB/32GB/64GB/128GB

but still wondering is there any better or easier way?

EDITED:

ok i got it... i really hate regular expression...

$pattern = '/[<td ?.*>](.*?)<\/td>/s';

this can solve the case if the string between td tags containing other tags... just a simple []...

OTHER TIPS

How about using preg_match_all:

$str='<td class="table_line_x_h10" width="647" align="left">&nbsp;16GB/<span style="color:red;">32GB</span>/64GB<br/>128GB</td>';
preg_match_all('/(\d+GB)/i', $str, $m);
print_r($m);                                                          

output:

Array
(
    [0] => Array
        (
            [0] => 16GB
            [1] => 32GB
            [2] => 64GB
            [3] => 128GB
        )

    [1] => Array
        (
            [0] => 16GB
            [1] => 32GB
            [2] => 64GB
            [3] => 128GB
        )

)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top