WordPress:过滤链接中某些字符串的内容并将元素更改为span

问题描述 投票:1回答:1

我正在使用WordPress,我想过滤包含特定字符串的链接的the_content。如果链接包含该字符串,则应将某个类添加到该元素,并且应将a元素替换为没有任何属性的span

链接模式:<a href="https://example.com/specific-string/file.pdf" title="Title">Link</a>

特定字符串:specific-string

如果链接包含特定字符串,则输出:<span class="private">Link</span>

所以我可以使用以下WordPress过滤器:

add_filter( 'the_content', 'the_content_filter_links', 10, 1 ); 

function the_content_filter_links( $value ) {

    // 1. Find all links that contain the string `specific-string`
    // 2. Remove all attributes from `a` tag.
    // 3. Change opening and closing `a` tags to `span`.

    // Output the content
    return $value; 
}; 

我发现this可以获取PHP中的所有链接,但是它利用了DOMDocument类,我认为在我的情况下无法使用它?

旁注:我不想为此使用JS,因为我不希望用户看到禁用JS的链接。

非常感谢您的帮助!

php regex wordpress preg-replace str-replace
1个回答
0
投票

您应该可以使用DOM:

© www.soinside.com 2019 - 2024. All rights reserved.