0

i am trying to get data between two <span...</span> that has specific color #ff0000 using the following code but i getting no data! could any one tell me what i am doing wrong ?

example of data:

<span style="color: #ff0000;">get this text1</span> |
<span style="color: #ff0000;">get this text2</span> |
<span style="color: #ff0000;">get this text3</span> |
<span style="color: #ff0000;">get this text4</span> |

php code:

if(preg_match_all("/<span style=\"color: #ff0000;\">(.*?)</span>/i", $code2, $epititle))
{
print_r($epititle[2]);
}
user1788736
  • 2,727
  • 20
  • 66
  • 110

3 Answers3

3

Don't parse HTML with regexes. If you do, a little kitten will die();

Stable solution is to use DOM:

$doc = new DOMDocument();
$doc->loadHTML($html);

foreach($doc->getElementsByTagName('span') as $span) {
    echo $span->nodeValue;
}

Notice that DOMDocument can gracefully parse HTML snippets as well, like this:

$doc->loadHTML('<span style="color: #ff0000;">get this text1</span>');
havana
  • 110
  • 5
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
2

Although I also recommend to use a DOM parser, here's a working version of your regexp:

if(preg_match_all("%<span style=\"color: #ff0000;\">(.*?)</span>%i", $code2, $epititle))

Only changes I made: I changed the delimiters from / to % because a slash is also used in </span>

The full output (print_r($epititle);) is:

Array
(
    [0] => Array
        (
            [0] => <span style="color: #ff0000;">get this text1</span>
            [1] => <span style="color: #ff0000;">get this text2</span>
            [2] => <span style="color: #ff0000;">get this text3</span>
            [3] => <span style="color: #ff0000;">get this text4</span>
        )

    [1] => Array
        (
            [0] => get this text1
            [1] => get this text2
            [2] => get this text3
            [3] => get this text4
        )

)
Reeno
  • 5,720
  • 11
  • 37
  • 50
0
$code2 = '<span style="color: #ff0000;">get this text1</span>';

preg_match_all("/<span style=\"color: #ff0000;\">(.*?)<\/span>/i", $code2, $epititle);

print_r($epititle);

Output

Array ( 
    [0] => Array (  [0] => get this text1 ) 
    [1] => Array ( [0] => get this text1 ) 
)