[英]Replacing HTML tag HREF based on its InnerHTML
I'm looking for a way to transform this: 我正在寻找一种方法来改变这一点:
...<a href="showinfo:3875//[integer]">[inner content]</a>...
Into this: 变成这个:
...<a href="http://somelink.com/[inner content]">[inner content]</a>...
The context has multiple links a with other showinfo:[integer] values. 上下文具有与其他showinfo:[integer]值的多个链接。 (I can process those ones)
(我可以处理那些)
Thanks for any help, Bálint 感谢您的帮助,巴林
Edit: Thanks to Kaiser's answer, here is the working snippet: 编辑:由于凯撒的答案,这是工作片段:
$html = $a;
$dom = new \DOMDocument;
@$dom->loadHTML( $html ); //Cannot guarantee all-valid input
foreach ($dom->getElementsByTagName('a') as $tag) {
// Fixed strstr order and added a != false check - the, because the string started with the substring
if ($tag->hasAttribute('href') && strstr($tag->getAttribute('href'), 'showinfo:3875') != false) {
$tag->setAttribute( 'href', "http://somelink.com/{$tag->textContent}");
// Assign the Converted HTML, prevents failing when saving
$html = $tag;
}
}
return $dom->saveHTML( $dom);
}
You can use DOMDocument
for a pretty reliable and fast way to handle DOM nodes and their attributes, etc. Hint: Much faster and more reliable than (most) Regex. 您可以使用
DOMDocument
获得一种可靠且快速的方式来处理DOM节点及其属性等。提示:比(大多数)Regex更快,更可靠。
// Your original HTML
$html = '<a href="showinfo:3875//[integer]">[inner content]</a>';
$dom = new \DOMDocument;
$dom->loadHTML( $html );
Now that you have your DOM ready, you can use either the DOMDocument
methods or DOMXPath
to search through it and obtain your target element. 现在,您已经准备好DOM,可以使用
DOMDocument
方法或DOMXPath
来搜索它并获取目标元素。
Example with XPath: XPath示例:
$xpath = new DOMXpath( $dom );
// Alter the query to your needs
$el = $xpath->query( "/html/body/a[href='showinfo:']" );
or for example by ID with the DOMDocument
methods: 或例如使用
DOMDocument
方法的ID:
// Check what we got so we have something to compare
var_dump( 'BEFORE', $html );
foreach ( $dom->getElementsByTagName( 'a' ) as $tag )
{
if (
$tag->hasAttribute( 'href' )
and stristr( $tag->getAttribute( 'href' ), 'showinfo:3875' )
)
{
$tag->setAttribute( 'href', "http://somelink.com/{$tag->textContent}" );
// Assign the Converted HTML, prevents failing when saving
$html = $tag;
}
}
// Now Save Our Converted HTML;
$html = $dom->saveHTML( $html);
// Check if it worked:
var_dump( 'AFTER', $html );
It's as easy as that. 就这么简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.