正则表达式:如何 select <td> 的位置与 PHP

Regex: how to select <td> of the location with PHP

Html代码:

<div username="bob">
        <table>
                <tr>
                    <td>name</td>
                    <td>alex</td>
                </tr>
                <tr>
                    <td>location</td>
                    <td>London</td>
                </tr>
                <tr>
                    <td>id</td>
                    <td>123</td>
                </tr>
        </table>
    </div>

    <div username="apple">
        <table>
                <tr>
                    <td>name</td>
                    <td>david</td>
                </tr>
                <tr>
                    <td>id</td>
                    <td>321</td>
                </tr>
        </table>
    </div>

    <div username="pepper">
        <table>
                <tr>
                    <td>location</td>
                    <td>Bradford</td>
                </tr>
        </table>
    </div>

我想select用户名的位置。
例如:
鲍勃位置=伦敦,
苹果位置= return假,
胡椒位置=布拉德福德
我想使用正则表达式。

<div\s+username="pepper">(?:(?!<\/div>)[\s\S])*?location.*?\s+<td>([^<]*)

根据您的 needs.See demo.Grab 捕获或组尝试 this.Change 名称。

https://regex101.com/r/vD5iH9/67

$re = "/<div\s+username=\"pepper\">(?:(?!<\/div>)[\s\S])*?location.*?\s+<td>([^<]*)/i";
$str = "<div username=\"bob\">\n <table>\n <tr>\n <td>name</td>\n <td>alex</td>\n </tr>\n <tr>\n <td>location</td>\n <td>London</td>\n </tr>\n <tr>\n <td>id</td>\n <td>123</td>\n </tr>\n </table>\n </div>\n\n <div username=\"apple\">\n <table>\n <tr>\n <td>name</td>\n <td>david</td>\n </tr>\n <tr>\n <td>id</td>\n <td>321</td>\n </tr>\n </table>\n </div>\n\n <div username=\"pepper\">\n <table>\n <tr>\n <td>location</td>\n <td>Bradford</td>\n </tr>\n </table>\n </div>";

preg_match_all($re, $str, $matches);