How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Replacing Inline Styles with Semantic HTML via Regex

Converting inline styles like font-weight: bold into semantic <strong> tags is a classic content migration task. The goal is specific: transform <span style="font-weight: bold;">Foo</span> into <strong>Foo</strong> without touching other <span> elements that might be used for layout, spacing, or distinct typography.

A naive str_replace or a simple regular expression substitution will fail because the target string contains quotes and special characters. You need a pattern that matches the opening tag, captures the text content, and reconstructs the closing tag with the new semantic element.

The core challenge lies in capturing the inner content while ensuring you don't accidentally match nested tags or alter adjacent elements. A robust regex approach involves using delimiters and capture groups to isolate the content between the opening and closing <span> tags.

Crafting the Regular Expression

To achieve this replacement, we need a pattern that identifies the start of the specific span, captures everything inside it (excluding the closing tag), and then allows us to reconstruct the string with the new wrapper.

Here is a regex pattern tailored for this specific transformation:

$pattern = '/<span\s+style="font-weight:\s*bold;"[^>]*>(.*?)<\/span>/i';
$replacement = '<strong>$1</strong>';
$string = '<span style="font-weight: bold;">Foo</span><span class="highlight">Important</span>';

$result = preg_replace($pattern, $replacement, $string);

echo $result;
// Output: <strong>Foo</strong><span class="highlight">Important</span>

This pattern breaks down as follows:

  • /<span\s+style="font-weight:\s*bold;"[^>]*>/i: This matches the opening <span> tag. It specifically looks for the style attribute containing font-weight: bold;. The [^>]* part is crucial here; it consumes any additional attributes (like an ID or extra classes) that might exist after the style declaration, ensuring we match the exact tag regardless of how cluttered the attributes are. The i flag makes the match case-insensitive.
  • (.*?): This is a non-greedy capture group. It grabs the content inside the span. Non-greedy matching (?) is essential here to prevent it from consuming text up to the last closing tag in the string if there were multiple spans.
  • <\/span>: Matches the literal closing tag.

The replacement string '<strong>$1</strong>' uses $1 to insert the captured content from the first group, effectively swapping the semantic wrapper while preserving the text exactly as it was.

Handling Edge Cases and Limitations

While this regex solution works for standard HTML structures, real-world data often introduces complications. One significant pitfall is malformed HTML where the closing tag might be missing or misplaced. If a span lacks a closing </span>, the pattern will fail to match that specific instance, leaving it untouched. This is generally a safe behavior for a migration script; you don't want to accidentally corrupt broken tags by forcing a replacement on them.

Another consideration is content containing HTML entities within the text itself. If your source string is <span style="font-weight: bold;">Foo & Bar</span>, the regex handles it correctly because the capture group stops at the first </span> found by the engine, treating the & inside the text as literal characters, not an entity that terminates the tag.

However, be wary of nested spans. If you encounter <span style="font-weight: bold;"><span>Nested</span></span>, a simple regex might behave unexpectedly depending on how the inner content is structured. In such cases, the outer span technically has the correct style, but the inner structure complicates the "replace whole tag" strategy. A robust parser would be necessary there, but for flat content migration, this pattern remains effective.

Why Not Just Use a DOM Parser?

You might wonder why not load the string into a DOMDocument or use a library like dompdf's parser to traverse the tree and update nodes directly. That approach is indeed safer for complex, deeply nested documents because it understands the document tree hierarchy. However, it introduces overhead: you must instantiate a DOM object, load the HTML string, iterate through nodes, check attributes, and then serialize the result back to a string.

For a simple find-and-replace operation on a large batch of strings where performance matters, a well-crafted regex is significantly faster and requires fewer lines of code. It avoids the memory footprint of creating DOM trees for thousands of small snippets. Use the DOM approach when you need to manipulate the document structure extensively; use regex when you have a clear, deterministic pattern like font-weight: bold that you want to swap out globally.

If you are working within the Laravel ecosystem and dealing with massive content migrations, consider leveraging existing packages or services designed for HTML sanitization and transformation. LaravelCompany often provides resources on optimizing PHP workflows for large-scale data processing, which can be relevant when scaling such regex operations across thousands of records.

Our network