正则表达式从html中选择

时间:2015-08-13 09:25:20

标签: regex preg-match

我有这种文字,我希望提取以下文字

Company Name ASSOCIATES LLP
                    18-20, FLOOR,, BUILDING,
                    K MARG, NEW - 110001
                    Delhi
                    +(91)124-0000000
                    email@EMAIL.COM

这是代码块 我正在使用的正则表达式是/Name and address of the Employer(.*)<p>/,但这是选择直到最后<p>

<p><b>Certificate under Section 203 of the Income-tax Act, 1961 for tax deducted at source on salary
            </b></p>
        <p><b>Name and address of the Employer
            </b></p>
        <p>Company Name ASSOCIATES LLP
            18-20, FLOOR,, BUILDING,
            K MARG, NEW - 110001
            Delhi
            +(91)124-0000000
            email@EMAIL.COM
        </p>
        <p><b>Name and address of the Employee
            </b></p>
        <p>EMPLOYEE NAME
            EMPLOYEE ADDRESS HERE
        </p>
        <p><b>PAN of the Deductor
            </b></p>
        <p>ACHFS9000A
        </p>
        <p><b>TAN of the Deductor
            </b></p>
        <p>DELS50000E
        </p>

1 个答案:

答案 0 :(得分:1)

您可以使用DOMDocument和DOMXPath提取p标记的内容,该p标记是具有b子节点的Name and address of the Employer节点的下一个兄弟,其内容包含$xp->query("//p[contains(./b, 'Name and address of the Employer')]"); 此查询:

<?php
$html = <<<HTML
<p><b>Certificate under Section 203 of the Income-tax Act, 1961 for tax deducted at source on salary
        </b></p>
    <p><b>Name and address of the Employer
        </b></p>
    <p>Company Name ASSOCIATES LLP
        18-20, FLOOR,, BUILDING,
        K MARG, NEW - 110001
        Delhi
        +(91)124-0000000
        email@EMAIL.COM
    </p>
    <p><b>Name and address of the Employee
        </b></p>
    <p>EMPLOYEE NAME
        EMPLOYEE ADDRESS HERE
    </p>
    <p><b>PAN of the Deductor
        </b></p>
    <p>ACHFS9000A
    </p>
    <p><b>TAN of the Deductor
        </b></p>
    <p>DELS50000E
    </p>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$links = $xp->query("//p[contains(./b, 'Name and address of the Employer')]");
foreach ($links as $link) {
    echo $link->nextSibling->nodeValue;
}

请参阅PHP示例代码:

for(String winHandle : driver.getWindowHandles())
             {
                driver.switchTo().window(winHandle);
             }

请参阅IDEONE demo