我使用 PHP
DomDocument
类从 3000 多个帖子中提取所有 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实现链接的最终替换?我对任何其他方法持开放态度。