javascript - 如何编写正则表达式来动态更改产品 ID 和 anchor 标记

标签 javascript php html regex

我想从 anchor tag <a> 的正则表达式中提取所有产品 url

每个产品都有id在 anchor 标记中,仅更改一些字母。

如您所见<a id="ctl00_cphMain_rPdctG_.*"这里 id 是静态的,最多 ctl00_cphMain_rPdctG_对于所有产品,之后更改为 ctl01_hTitle , ctl02_hTitle像那样。

下面是我的代码

<?php
$html = file_get_contents("website url here");


    preg_match_all(
        '/<div class=\"pdct\-inf\">(.*?)<\/div>/s',
        $html,
        $posts    
    );

    print_r($posts). "\n";

    foreach ($posts as $posts) {

    $str = $posts[1][0];

    preg_match('/<a id="ctl00_cphMain_rPdctG_.*" href="(.*)">(.*)<\/a>/m',$str,$match);

    print_r($match) . "\n"; 
    print($match[2]) . "\n";

    }

现在,这为所有产品提供输出,并仅提供第一个产品的数组。

我想应用 for 循环来获取所有产品的数据,我可以将其存储在 php 变量中以导出到 csv..

需要对 for 循环进行一些修正。

当前输出 -

Array
(
    [0] => <a id="ctl00_cphMain_rPdctG_ctl01_hTitle" href="/whirlpool-whirlpool-direct-drive-285753a-ap3963893.html">Whirlpool Direct Drive Washer Mot...</a>
    [1] => /whirlpool-whirlpool-direct-drive-285753a-ap3963893.html
    [2] => Whirlpool Direct Drive Washer Mot...
)

Whirlpool Direct Drive Washer Mot...

所有产品的预期输出

所以$match[1]存储 url 和 $match[2]产品的变量商店名称。

如有任何帮助,我们将不胜感激。谢谢

<小时/>

编辑

如何添加 for 循环来更改 $posts[1][0] 的值

没有 For 循环的代码 -

<?php 

$html = file_get_contents("Website url here ");


preg_match_all(
    '/<div class=\"pdct\-inf\">(.*?)<\/div>/s',
    $html,
    $posts    
);
//echo "First row posts\n";
print_r($posts). "\n";

$str = $posts[1][0];


preg_match('/<a id="ctl00_cphMain_rPdctG_.*" href="(.*)">(.*)<\/a>/m',$str,$match);

echo "Second row match\n";
print_r($match) . "\n"; 

echo "Third  value \n";
print($match[2]) . "\n";

最佳答案

此处添加产品 ID <a>

     $i=1;
     foreach ($posts as $posts) {
     $i=str_pad($i, 2, "0", STR_PAD_LEFT);
     $str = $posts[1][0];
     preg_match('/<a id="ctl'.$i.'_cphMain_rPdctG_.*" href="(.*)">(.*)<\/a>/m',$str,$match);
     print_r($match) . "\n"; 
     print($match[2]) . "\n";
     $i++;
}

这里$posts['id']是您想要的产品 ID。或者您可以使用 $i=0; 添加常规,然后在循环内使用 $i++

关于javascript - 如何编写正则表达式来动态更改产品 ID 和 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35764307/

相关文章:

html - 幻灯片下拉打开

javascript - Sequelize.js ownsToMany 实例方法 create 不起作用?

javascript - 如何使用按键触发事件(ctrl +)(jQuery)

php - 数据库中的数据未显示

php - smarty 中的引用数组

php - 在从 MySQL 导出的 XML 中使用标签

javascript - 仅使用 JavaScript 使用自定义标签

html - CSS - 将页脚刷新到页面底部

javascript - 带样式显示的div :table has wrong height

javascript - 即使输入被隐藏,也要在输入文本旁边放置按钮?