我正在尝试制作一个正则表达式,用于从表中获取一些数据。
我现在的代码是:
<table>
<tr>
<td>quote1</td>
<td>have you trying it off and on again ?</td>
</tr>
<tr>
<td>quote65</td>
<td>You wouldn't steal a helmet of a policeman</td>
</tr>
</table>
我想替换为:
quote1:你有没有尝试过它?
quote65:你不会偷一个警察头盔
我已编写的代码是:
%<td>((?s).*?)</td>%
但现在我被卡住了。
答案 0 :(得分:4)
如果你真的想使用正则表达式(如果你真的确定你的字符串总是这样格式的话可能没问题),那么在你的情况下会是这样的:
$str = <<<A
<table>
<tr>
<td>quote1</td>
<td>have you trying it off and on again ?</td>
</tr>
<tr>
<td>quote65</td>
<td>You wouldn't steal a helmet of a policeman</td>
</tr>
</table>
A;
$matches = array();
preg_match_all('#<tr>\s+?<td>(.*?)</td>\s+?<td>(.*?)</td>\s+?</tr>#', $str, $matches);
var_dump($matches);
关于正则表达式的几句话:
<tr>
<td>
</td>
</tr>
我用:
?
以非贪婪模式匹配preg_match_all
获取所有比赛然后,您可以在$matches[1]
和$matches[2]
(不是$matches[0]
)中获得所需的结果;这是我使用 var_dump
的输出(我删除了条目0,使其更短):
array
0 =>
...
1 =>
array
0 => string 'quote1' (length=6)
1 => string 'quote65' (length=7)
2 =>
array
0 => string 'have you trying it off and on again ?' (length=37)
1 => string 'You wouldn't steal a helmet of a policeman' (length=42)
然后你需要操作这个数组,并使用一些字符串连接等;例如,像这样:
$num = count($matches[1]);
for ($i=0 ; $i<$num ; $i++) {
echo $matches[1][$i] . ':' . $matches[2][$i] . '<br />';
}
你得到:
quote1:have you trying it off and on again ?
quote65:You wouldn't steal a helmet of a policeman
注意:您应该添加一些安全检查(如preg_match_all
必须返回true,count必须至少为1,...)
作为旁注:使用正则表达式来解析HTML通常不是一个好主意;如果你可以使用真正的解析器,它应该更安全......
答案 1 :(得分:3)
答案 2 :(得分:1)
像往常一样,应该使用解析器从HTML和其他非常规语言中提取文本 - 正则表达式可能会导致问题。但是,如果您确定数据的结构,可以使用
%<td>((?s).*?)</td>\s*<td>((?s).*?)</td>%
找到两段文字。 \ 1:\ 2然后将被替换。
如果文本不能超过一行,那么删除(?s)
位会更安全......
答案 3 :(得分:0)
不要使用正则表达式,请使用HTML解析器。例如PHP Simple HTML DOM Parser
答案 4 :(得分:0)
从<td>
preg_match_all("%\<td((?s).*?)</td>%", $respose, $mathes);
var_dump($mathes);