0

How may I preg_match this in PHP?

$item[0] = <tr><td rowspan=2>07/07/2016 14:55</td><td>AC MENDES - Mendes/RJ</td><td><font color="000000">Postado depois do horário limite da agência</font></td></tr>

I've tried the code below, but it didn't work...

if(preg_match("@<td rowspan=[2]>(.*)</td><td>(.*)</td><td><FONT COLOR=\"[0-9A-F]{6}\">(.*)</font></td>@", $item[0], $d))
{
  echo 'OK';
}
William
  • 1,010
  • 3
  • 21
  • 39

1 Answers1

1

You may use a DOM with XPath to get all TD texts:

$html = <<<DATA
<tr><td rowspan=2>07/07/2016 14:55</td><td>AC MENDES - Mendes/RJ</td><td><font color="000000">Postado depois do horário limite da agência</font></td></tr>;
DATA;
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
$tds = $xpath->query('//td');
$res = array();
foreach($tds as $td) { 
   array_push($res, $td->nodeValue);
}
print_r($res);

See the PHP demo

The //td will get all td nodes. You might also be using '//text()' XPath to just grab all text nodes.

Else, if you know what you are doing, you may add some temporary strings after each <td> node and then strip tags and explode right with the temporary string:

explode("###", strip_tags(str_replace("<td>", "<td>###", $s)))

See this demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563