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

PHP preg_replace匹配模式:移除class为reference的span标签内内容

Solution for Replacing Content in <span class="reference"> with Variable data-code

Got it, let's fix this for you. The issue with your current regex is that you've hardcoded the data-code="Z22" value, so it can't handle cases where that code changes. Here are two reliable approaches to solve this:

1. Updated Regular Expression (Simple HTML Scenarios)

If your HTML structure is consistent (no weird edge cases like attribute order swapping or escaped quotes), you can tweak the regex to match any data-code value instead of a fixed one.

Modified Code:

$string = 'Some text &lt;span class="reference" data-code="Z22"&gt;Data code&lt;/span&gt; More text &lt;span class="reference" data-code="X11"&gt;Another reference&lt;/span&gt;';
// Regex now matches ANY data-code value (using [^"]+ to capture all non-quote characters)
$pattern = '|(?&lt;=&lt;span class=\"reference\" data-code=\"[^\"]+\"&gt;)(.*?)(?=&lt;\/span&gt;)|';
$replace = '&lt;a href=""&gt; replaced &lt;/a&gt;';
// Use preg_replace instead of looping through matches for cleaner code
$modifiedString = preg_replace($pattern, $replace, $string);

echo $modifiedString;

How It Works:

  • [^\"]+ replaces the hardcoded Z22 — this matches any sequence of characters that aren't double quotes, so it works for any data-code value (letters, numbers, mixed characters, etc.).
  • preg_replace handles all matching spans in one go, so you don't need to loop through matches manually.

2. DOMDocument Approach (Robust for Complex HTML)

Regex can break if your HTML has unexpected variations (like data-code coming before class, or extra attributes in the span). For a more reliable solution, use PHP's built-in DOM parsing tools:

Code Example:

$string = 'Some text &lt;span class="reference" data-code="Z22"&gt;Data code&lt;/span&gt; More text &lt;span class="reference" data-code="X11"&gt;Another reference&lt;/span&gt;';

// Initialize DOMDocument and handle potential HTML parsing warnings
libxml_use_internal_errors(true);
$dom = new DOMDocument();
// Load HTML without adding default doctype/html/body tags
$dom->loadHTML(htmlspecialchars_decode($string), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

// Use XPath to find all span tags with class="reference"
$xpath = new DOMXPath($dom);
$referenceSpans = $xpath->query('//span[@class="reference"]');

foreach ($referenceSpans as $span) {
    // Create the replacement <a> tag
    $replacementLink = $dom->createElement('a');
    $replacementLink->setAttribute('href', '');
    $replacementLink->nodeValue = ' replaced ';
    
    // Clear the span's current content and add the new link
    $span->nodeValue = '';
    $span->appendChild($replacementLink);
}

// Convert back to escaped HTML string
$modifiedString = htmlspecialchars($dom->saveHTML());
echo $modifiedString;

Why This Is Better:

  • It doesn't care about attribute order or extra attributes in the span — it reliably targets all spans with class="reference", regardless of their data-code value.
  • Avoids regex pitfalls with malformed or unpredictable HTML.

Choose the first method if your HTML is simple and consistent, and the second if you need to handle more flexible or complex HTML structures.

内容的提问来源于stack exchange,提问作者D. Vasiliev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:11:36