【问题标题】:preg_replace second parameter ($replacement) doesnt fitpreg_replace 第二个参数($replacement)不适合
【发布时间】: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。

标签: php html regex wordpress


【解决方案1】:

找到了解决方案。感谢您的时间。

   if(preg_match_all('/href\s*=\s*"[^"]+(#[^"]+)"/',get_the_content(),$match))
    {
    echo preg_replace('/href\s*=\s*"[^"]+(#[^"]+)"/','href="$1"', get_the_content()); 
    }  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多