gpt4 book ai didi

php - 查找并 append 某个类的 href

转载 作者:行者123 更新时间:2023-12-01 23:10:30 24 4
gpt4 key购买 nike

我一直在寻找解决方案,但尚未找到正确的方法。

情况是这样的:我需要查找页面上具有给定类的所有链接(例如 class="tracker"),然后在末尾 append 查询字符串值,因此当用户加载页面时,这些特定链接是更新了一些动态信息。

我知道如何使用 Javascript 来完成此操作,但我真的很想对其进行调整以运行服务器端。我对 PHP 还很陌生,但从它的外观来看,XPath 可能就是我正在寻找的东西,但我还没有找到合适的示例来开始和。有类似 GetElementByClass 的东西吗?

任何帮助将不胜感激!

暗影

最佳答案

Is there anything like GetElementByClass?

这是我发起的一个实现...

function getElementsByClassName(DOMDocument $domNode, $className) {
$elements = $domNode->getElementsByTagName('*');
$matches = array();
foreach($elements as $element) {
if ( ! $element->hasAttribute('class')) {
continue;
}
$classes = preg_split('/\s+/', $element->getAttribute('class'));
if ( ! in_array($className, $classes)) {
continue;
}
$matches[] = $element;
}
return $matches;
}

此版本不依赖上面的辅助函数。

$str = '<body>
<a href="">a</a>
<a href="http://example.com" class="tracker">a</a>
<a href="http://example.com?hello" class="tracker">a</a>
<a href="">a</a>
</body>
';

$dom = new DOMDocument;

$dom->loadHTML($str);

$anchors = $dom->getElementsByTagName('body')->item(0)->getElementsByTagName('a');

foreach($anchors as $anchor) {

if ( ! $anchor->hasAttribute('class')) {
continue;
}

$classes = preg_split('/\s+/', $anchor->getAttribute('class'));

if ( ! in_array('tracker', $classes)) {
continue;
}

$href = $anchor->getAttribute('href');

$url = parse_url($href);

$attach = 'stackoverflow=true';

if (isset($url['query'])) {
$href .= '&' . $attach;
} else {
$href .= '?' . $attach;
}

$anchor->setAttribute('href', $href);
}

echo $dom->saveHTML();

输出

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<a href="">a</a>
<a href="http://example.com?stackoverflow=true" class="tracker">a</a>
<a href="http://example.com?hello&amp;stackoverflow=true" class="tracker">a</a>
<a href="">a</a>
</body></html>

关于php - 查找并 append 某个类的 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com