php正则表达式可选字段

时间:2015-07-23 15:27:09

标签: php regex parsing

我似乎把自己与我正在做的preg_match正则表达混淆了,所以新的眼睛和帮助将会受到赞赏。

我现在的正则表达式如下:

<div>

但有时候没有给出一些列,那么将字段标记为可选的最佳解决方案是什么?

表格如下:

http://pastebin.com/wBRXhJDP

任何建议都会很好; - )

1 个答案:

答案 0 :(得分:0)

You shouldn't use regular expressions to parse HTML.

这是一个快速脚本,用于创建一个充满键和值的数组:

<?php
$str = <<< ENDL
<table cellpadding="2" cellspacing="0" border="0" align="center">
    <tr>
        <td width="120" valign="top">Server Status: </td>
        <td><b>Server is currently up and public</b></td>
    </tr>
    <tr>
        <td valign="top">Stream Status: </td>
        <td><b>Stream is up at 256 kbps with 0 of 250 listeners</b></td>
    </tr>
    <tr>
        <td valign="top">Listener Peak: </td>
        <td><b>1</b></td>
    </tr>
    <tr>
        <td valign="top">Average Listen Time: </td>
        <td><b>1 hours 50 minutes 8 seconds</b></td>
    </tr>
    <tr>
        <td valign="top">Stream Name: </td>
        <td><b><a target="_blank" href="http://www.shoutcast.com/Internet-Radio/XYZ">XYZ</a></b></td>
    </tr>
    <tr>
        <td valign="top">Content Type: </td>
        <td><b>audio/aacp</b></td>
    </tr>
    <tr>
        <td valign="top">Stream Genre: </td>
        <td><b>Jazz</b></td>
    </tr>
    <tr>
        <td valign="top">Stream URL: </td>
        <td><b><a target="_blank" href="http://tmp/">http://tmp/</a></b></td>
    </tr>
    <tr>
        <td valign="top">Current Song: </td>
        <td><b><a href="currentsong?sid=1">test</a></b></td>
    </tr>
    <tr>
        <td valign="top">Next Song: </td>
        <td><b><a href="nextsong?sid=1">test2</a></b></td>
    </tr>
</table>  
ENDL;

$html = new SimpleXMLElement($str);
$buffer = array();

foreach($html->tr as $row) {
  $label = trim(rtrim(trim($row->td[0]), ":"));
  $value = trim(strip_tags($row->td[1]->asXML()));
  $buffer[$label] = $value;
}

echo "<pre>";
var_dump($buffer);
echo "</pre>";

结果:

array(10) {
  ["Server Status"]=>
  string(33) "Server is currently up and public"
  ["Stream Status"]=>
  string(48) "Stream is up at 256 kbps with 0 of 250 listeners"
  ["Listener Peak"]=>
  string(1) "1"
  ["Average Listen Time"]=>
  string(28) "1 hours 50 minutes 8 seconds"
  ["Stream Name"]=>
  string(3) "XYZ"
  ["Content Type"]=>
  string(10) "audio/aacp"
  ["Stream Genre"]=>
  string(4) "Jazz"
  ["Stream URL"]=>
  string(11) "http://tmp/"
  ["Current Song"]=>
  string(4) "test"
  ["Next Song"]=>
  string(5) "test2"
}