bsteo bsteo - 12 days ago 5
PHP Question

PHP return multiple matches same REGEX pattern

I have the following "text":

<tr valign="top">
<td>Name:</td>
<td>John Doe</td>
</tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr valign="top">
<td>Address:</td>
<td>71 view st, Fitchburg, MA 01420</td>
</tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr valign="top">
<td>Phone:</td>
<td>978-345-5391</td>
</tr>
<tr><td colspan="2">&nbsp;</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:

$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 ok. Maybe I don't understand how REGEX works, isn't possible to have more matches in a single pattern?

Answer

Example showing multiline regex. 1. Not best solution to problem but illustrates ability. 2. Not the best regex but the point is the s flag at the end.

<?php
$html = <<<EOL
<tr valign="top">
        <td>Name:</td>
        <td>John Doe</td>
</tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr valign="top">
        <td>Address:</td>
        <td>71 view st, Fitchburg, MA 01420</td>
</tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr valign="top">
        <td>Phone:</td>
        <td>978-345-5391</td>
</tr>
<tr><td colspan="2">&nbsp;</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]);
}


?>

Yeilds

Name: John Doe
Address: 71 view st, Fitchburg, MA 01420
Phone: 978-345-5391
Email: johndoe@cs.com
Comments