【发布时间】:2013-11-03 20:33:25
【问题描述】:
我在 Wordpress 中的帖子内容是一个很大的标记。它来自 MS Word,因此它是由 HTML 嵌套标签和内联样式包裹的文本。
我有一段代码在内容中重复了很多次(它代表文本脚注)。这一段,例如第一个脚注是:
<sup><a title="" href="file:///C:/Users/hp/Desktop/file.docx#_ftn1" name="_f
tnref1">
<span class="MsoFootnoteReference">
<span dir="LTR">
<span class="MsoFootnoteReference">
<span lang="EN-US" style="font-size: 16pt; line-height: 115%;">
[1]
</span>
</span>
</span>
</span>
</a></sup>
.....
<a title="" href="file:///C:/Users/hp/Desktop/file.docx#_ftnref1" name="_ftn1">
<span class="MsoFootnoteReference">
<span dir="LTR" lang="EN-US" style="font-size: 12.0pt; font-family: 'Simplified Arabic','serif';">
<span class="MsoFootnoteReference">
<span lang="EN-US" style="font-size: 12pt; line-height: 115%;">
[1]
</span>
</span>
</span>
</span>
</a>
我的目标是从以下位置更改 2 个 href:
href="file:///C:/Users/hp/Desktop/file.docx#_ftn1"
href="file:///C:/Users/hp/Desktop/file.docx#_ftnref1"
到:
href="#_ftn1"
href="#_ftnref1"
这样用户就可以从一个锚点跳到另一个锚点。
我使用的代码是:
if(preg_match_all('/href\s*=\s*"[^"]+(#[^"]+)"/',get_the_content(),$match))
{
echo preg_replace('/href\s*=\s*"[^"]+(#[^"]+)"/','href=""', get_the_content());
}
非常感谢您的宝贵帮助。
【问题讨论】:
-
请注意,HTML 不能用正则表达式表示。使用健壮的 HTML DOM 解析器/处理器,例如 BeautifulSoup/libhtml5 用于 Python。