[英]PHP return multiple matches same REGEX pattern
I have the following HTML: 我有以下HTML:
<tr valign="top">
<td>Name:</td>
<td>John Doe</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr valign="top">
<td>Address:</td>
<td>71 view st, Fitchburg, MA 01420</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr valign="top">
<td>Phone:</td>
<td>978-345-5391</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr>
<td>Email:</td>
<td>johndoe@cs.com</td>
</tr>
I want to capture the values of Name
, Phone
and Email
within the same REGEX pattern, something like: 我想在相同的REGEX模式下捕获Name
, Phone
和Email
的值,例如:
$pattern = "/Name:<\/td>\s*<td>(.*)<\/td>.*Address:<\/td>\s*<td>(.*)<\/td>.*card ([0-9].*)<\/td>/m";
If I try separately, like: 如果我单独尝试,例如:
$pattern = "/Name:<\/td>\s*<td>(.*)<\/td>/m";
$pattern = "/Phone:<\/td>\s*<td>(.*)<\/td>/m";
$pattern = "/Email:<\/td>\s*<td>(.*)<\/td>/m";
is okay. 没关系。 Maybe I don't understand how REGEX works, isn't possible to have more matches in a single pattern? 也许我不了解REGEX的工作原理,是否不可能在单个模式中进行更多匹配?
Example showing multiline regex. 显示多行正则表达式的示例。 1. Not best solution to problem but illustrates ability. 1.不是解决问题的最佳方法,而是说明能力。 2. Not the best regex but the point is the s
flag at the end. 2.不是最好的正则表达式,但重点是末尾的s
标志。
<?php
$html = <<<EOL
<tr valign="top">
<td>Name:</td>
<td>John Doe</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr valign="top">
<td>Address:</td>
<td>71 view st, Fitchburg, MA 01420</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr valign="top">
<td>Phone:</td>
<td>978-345-5391</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr>
<td>Email:</td>
<td>johndoe@cs.com</td>
</tr>
EOL;
$pattern = "#Name:</td>.*<td>(.*?)</td>.*Address:</td>.*<td>(.*?)</td>.*Phone:</td>.*<td>(.*?)</td>.*Email:</td>.*<td>(.*?)</td>#s";
if(preg_match($pattern, $html, $matches)) {
printf("Name: %s\n", $matches[1]);
printf("Address: %s\n", $matches[2]);
printf("Phone: %s\n", $matches[3]);
printf("Email: %s\n", $matches[4]);
}
?>
Yields 产量
Name: John Doe
Address: 71 view st, Fitchburg, MA 01420
Phone: 978-345-5391
Email: johndoe@cs.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.