提问人:TheBigK 提问时间:1/12/2023 最后编辑:halferTheBigK 更新时间:2/26/2023 访问量:39
使用 DomDocument 更改数千个帖子中的<a>
Altering <a> in thousands of posts with DomDocument
问:
我使用 PHP 类从 3000 多个帖子中提取所有标签,并将它们收集到数据库中,如下所示 -DomDocument
a
我使用函数来填充表格。domDocument
C14N()
existing_link
id | existing_link | replacement_link
1 | <a class="class1" href="domain1.com" rel="nofollow">Domain1.com</a> | <a href="domain2.com">Domain2.com</a>
我最初的想法是简单地使用 Laravel 来查找和替换上表中的链接。但是,做了一些我没有想到的事情。它按字母顺序排列链接的属性。也就是说,虽然我帖子中的链接以 -Str::replace()
C14N()
<a href="domain1.com" class="class1" rel="nofollow">Domain1.com</a>
C14N() 函数保存了它,属性顺序发生了变化(class -> href -> rel)!请看上表。existing_link
因此,我无法使用 Laravel 的快速替换链接;即使它们在技术上是相同的链接;它们不是相同的字符串。Str::replace()
我的数据库中的每个帖子都可以根据我准备的表格替换多个链接。到目前为止,我最好的尝试如下——
$new_links = DB::table('links')->get();
foreach ($new_links as $new_link)
{
$post = Post::where('id', $new_link->id)->first();
$post_body = $post->body;
$domDocument = new \DOMDocument();
$domDocument->loadHTML($post_body, LIBXML_NOERROR);
// Pull the links in the post body
$old_links = $domDocument->getElementsByTagName('a');
foreach ($old_links as $old_link)
{
if($old_link->C14N() == $new_link->existing_link)
{
// Perform the replacement. I can't figure out how to do this using DOMDOcument.
}
}
}
如何使用 DOMDocument 实现链接的最终替换?我对任何其他方法都持开放态度。
答: 暂无答案
评论
str_replace()
C14N()