正则表达式:如何使用 PHP 选择位置的 <td>


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>

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

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

试试这个。根据需要更改名称。请参阅演示。抓取捕获或组。

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);