删除锚标记并使用正则表达式以数组形式获取内部文本

Remove anchor tag and get inner text in an array form using regular expression

本文关键字:数组 获取 文本 内部 正则表达式 删除      更新时间:2023-09-26

我使用这个代码删除锚标记,也只得到内部文本使用表达式

    <ul class="alpha">
                <li><h3><a href="http://www.overstock.com/Electronics/Computers-Tablets/473/dept.html?TID=TN:ELEC:Comp">Computers &amp; Tablets</a></h3></li>
                <li><a href="http://www.overstock.com/Electronics/2-in-1s/28195/subcat.html?TID=TN:ELEC:2in1">2-in-1s</a></li>
                <li><a href="http://www.overstock.com/Electronics/Laptops/133/subcat.html?TID=TN:ELEC:Lap">Laptops</a></li>
</ul>

表达式是:

echo preg_replace('#<a.*?>([^>]*)</a>#i', '$1', $str);

输出是:

Computers & Tablets
2-in-1s
Laptops

我们可以得到内部文本内锚标记在数组形式使用正则表达式?请分享你的想法。

我不喜欢你使用HTML与regex而是使用DomDocument但如果你想使用regex比你可以使用preg_match_all

preg_match_all('/(?:(<a.*?>))(.*?)(?=<'/a>)/', '<ul class="alpha">
                <li><h3><a href="http://www.overstock.com/Electronics/Computers-Tablets/473/dept.html?TID=TN:ELEC:Comp">Computers &amp; Tablets</a></h3></li>
                <li><a href="http://www.overstock.com/Electronics/2-in-1s/28195/subcat.html?TID=TN:ELEC:2in1">2-in-1s</a></li>
                <li><a href="http://www.overstock.com/Electronics/Laptops/133/subcat.html?TID=TN:ELEC:Lap">Laptops</a></li>
</ul>',$res);
print_r($res[0]);
输出:

Array
(
    [0] => Computers & Tablets
    [1] => 2-in-1s
    [2] => Laptops
)

由于您使用了jQuery标记,所以我更倾向于在jQuery中执行此操作:

var values = [];
$('.alpha').find('a').each(function(index){
    values.push($(this).text());
});

此代码获取.alpha类中的所有链接并将它们压入values数组。values的输出为:

0: "Computers & Tablets"
1: "2-in-1s"
2: "Laptops"