使用preg_match_all匹配含特殊字符的精确内容并替换为带类的span
Fixing the Exact Match & Replacement for Your WordPress Content Cleaner
Let's break down what's going wrong with your current function and fix it properly:
Key Issues in Your Current Code
- Your regex matches all
<strong>tags instead of only those containing exactly* * * - The
*character is a special regex metacharacter—you need to escape it to match the literal asterisks - Your function stops after replacing the first match, leaving any additional instances untouched
- You're using
str_replacein a loop which is inefficient and error-prone for regex-based replacements
Updated Function with Correct Regex & Logic
Here's the optimized version that addresses all these problems:
function content_format_stars($str = null) { if (empty($str)) { return $str; } // Target the exact escaped HTML pattern: <strong>* * *</strong> (as HTML entities) // \s* allows for optional whitespace around the asterisks (adjust if you need strict matching) $pattern = '#<strong[^>]*>\s*\*\s*\*\s*\*\s*</strong>#'; $replacement = '<span class="crb-content-divider">* * *</span>'; // Replace ALL matching instances in one go with preg_replace return preg_replace($pattern, $replacement, $str); }
What Changed & Why
Precise Regex Pattern:
\*escapes the asterisk to match the literal character instead of using it as a regex wildcard\s*accounts for any optional whitespace (spaces, tabs) around the asterisks—remove this if you need exact* * *with single spaces only<strong[^>]*>matches any<strong>tag (including those with attributes likeclassorid) without breaking the match
Efficient Replacement:
- Using
preg_replaceinstead ofpreg_match_all+ loop lets you replace all matching instances in one line, no need to manually iterate through matches - We avoid early
returnstatements that stopped processing after the first match
- Using
Robust Edge Handling:
- The initial
empty($str)check is simplified for readability - The function returns the original string if no matches are found (preg_replace does this automatically)
- The initial
Example Usage
If your input content looks like this:
<p>Some regular text</p> <strong>* * *</strong> <p>More text</p> <strong class="some-class">* * *</strong> <strong>This is a normal strong tag</strong>
The output will be:
<p>Some regular text</p> <span class="crb-content-divider">* * *</span> <p>More text</p> <span class="crb-content-divider">* * *</span> <strong>This is a normal strong tag</strong>
Strict Matching (Optional)
If you need to match only <strong> tags with exactly * * * (no extra whitespace, no attributes), use this pattern instead:
$pattern = '#<strong>\* \* \*</strong>#';
内容的提问来源于stack exchange,提问作者Kyle Knight
相关产品推荐
相关产品推荐

