简体   繁体   English

仅在有此HTML标签的情况下才如何进行匹配?

[英]How to preg match only if there is this HTML tag?

As shown below in the code, it gets all the matches that have 10 digits and it works great. 如下代码所示,它可以获取所有具有10位数字的匹配项,并且效果很好。 However I need to filter the matches only with these that are inside this tag 但是我只需要使用此标记内的匹配项来过滤匹配项

<tr class="main_row pc">

Other numbers are inside this tag (pc is changed to dc) 其他数字在此标记内(pc更改为dc)

<tr class="main_row dc">

.

$html= file_get_contents('...');
$matches = array();
preg_match_all('/\d{10}/', $html, $matches);
   foreach ($matches[1] as $match) {
    echo $match.'<br>';
}

How can I filter the numbers? 如何过滤数字?

UPDATE this is the HTML. 更新这是HTML。 I want to get the 6914576304 but because there is this tag <tr class="main_row pc"> 我想获取6914576304,但是因为有此标签<tr class="main_row pc">

<tr class="main_row pc">
    <td class="details">
        <a href="./view/4135660/"><span class="p_t">Fiat Cinquecento </span></a>
        <a class="info" href="./view/4135660/">(Info)</a><br>
        <div class="attribs">16345, <span class="p_l">Blue</span>, Phone 6914576304
        </div>
    </td>
</tr>

How about instead of /\\d{10}/ , do: 如何代替/\\d{10}/来做:

/<tr class="main_row pc">\d{10}<\/tr>/

You could simplify that too, but I don't know if it's important to you that the number be inside of a tr with both classes specifically or not. 您也可以简化它,但是我不知道数字是否在两个类的tr内部特别重要。 Here's some example code and its output: 这是一些示例代码及其输出:

<?php

$data = '<tr class="main_row pc">0123456789</tr><tr class="main_row pc">1123456789</tr><tr class="main_row dc">2123456789</tr>';

$matches = array();
preg_match_all('/<tr class="main_row pc">\d{10}<\/tr>/', $data, $matches);
print_r($matches);

?>

Output: 输出:

Array
(
    [0] => Array
        (
            [0] => <tr class="main_row pc">0123456789</tr>
            [1] => <tr class="main_row pc">1123456789</tr>
        )
)

The first two are matched, the last one is a different class, and is ignored. 前两个匹配,最后一个是不同的类,将被忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM