You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中使用str_replace仅替换页面文本而不影响HTML标签?

Solution: Use DOM Parsing to Target Only Visible Text Nodes

The core issue with your current code is that str_replace operates on the entire HTML string, including attribute values inside tags—so it can’t tell the difference between visible content and stuff like class names or href values. To fix this, we need to parse the HTML structure and only modify actual text nodes (the content users see), leaving tag attributes and code blocks untouched.

Here’s a revised implementation using PHP’s DOMDocument and DOMXPath to safely target just visible text:

function shuffle_word($word) {
    // Only process words longer than 3 characters and made purely of letters
    if (strlen($word) > 3 && ctype_alpha($word)) {
        $first = substr($word, 0, 1);
        $last = substr($word, -1);
        $middle = substr($word, 1, -1);
        // Shuffle the middle characters and reconstruct the word
        return $first . str_shuffle($middle) . $last;
    }
    return $word;
}

function replace_text_wps($content) {
    // Skip empty or non-string content
    if (empty($content) || !is_string($content)) {
        return $content;
    }

    // Suppress minor DOM parsing warnings (common with messy HTML)
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    // Load content with UTF-8 encoding to avoid character mangling
    $dom->loadHTML('<?xml encoding="UTF-8">' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    // Target text nodes, excluding those inside script, style, or code tags
    $textNodes = $xpath->query('//text()[not(ancestor::script) and not(ancestor::style) and not(ancestor::code)]');

    foreach ($textNodes as $node) {
        $text = $node->nodeValue;
        // Split text into words and non-word parts (preserves punctuation/spaces)
        $parts = preg_split('/(\s+|[^\w\'])/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
        $processedParts = array_map(function($part) {
            // Only shuffle actual words; leave punctuation/spaces as-is
            return ctype_alpha($part) ? shuffle_word($part) : $part;
        }, $parts);
        $node->nodeValue = implode('', $processedParts);
    }

    return $dom->saveHTML();
}
add_filter('the_content', 'replace_text_wps', 99);

Key Improvements:

  • DOM Parsing: Properly parses HTML to distinguish between visible text and tag attributes, so we never accidentally modify class names or links.
  • XPath Filtering: Excludes text inside <script>, <style>, and <code> tags—we don’t want to shuffle code or styles that break functionality.
  • Smart Text Splitting: Uses regex to split text into words and non-word elements (like commas, spaces), ensuring punctuation and whitespace stay intact.
  • Encoding Safety: Adds a UTF-8 declaration to prevent special characters from getting mangled during parsing.

How It Works:

  1. The shuffle_word function handles the core word-modification logic, extracted into a reusable function for clarity.
  2. The main replace_text_wps function loads the HTML content, uses XPath to find all relevant text nodes.
  3. For each text node, we split the content into parts, process only the actual words, then recombine everything to preserve formatting.
  4. Finally, we convert the modified DOM back to an HTML string and return it.

This approach guarantees you only modify the content users can see, leaving your HTML structure and functionality completely intact.

内容的提问来源于stack exchange,提问作者Anmol Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:23:11