get everything between <tag> and </tag> with php

get everything between <tag> and </tag> with php

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

Stefan Bogdanescu

Founder & Senior Architect

Extracting HTML Content Between Tags in PHP

You are attempting to extract everything between <code> and </code> tags from a string. The challenge here isn't just matching the delimiters; it's capturing the content between them while preserving the integrity of the original string for replacement operations. Regex is capable of this, but the patterns you've tried indicate a common misunderstanding of how capture groups work in combination with non-capturing quantifiers.

Your first attempt uses $regex = "/<code\s*(.*)\&gt;(.*)&lt;\/code&gt;/". The issue lies in the greedy nature of the .* quantifier. In your pattern, the first .* will consume as much text as possible, including the closing tag content, to satisfy the regex engine before it backtracks to find the second .*. Furthermore, the logic of splitting the content into two separate groups ((.*) and (.*)) complicates the replacement step significantly because you are trying to reconstruct the exact original substring.

To extract the content reliably, you need a single capture group that matches everything between the opening tag and the closing tag, excluding the tags themselves. The correct approach for your specific string manipulation goal is:

$regex = '/<code>(.*?)<\/code>/';

The key modification here is the use of (.*?) instead of (.*). By default, .* is greedy, meaning it matches as much text as possible. You want a non-greedy match (lazy quantifier), so the engine stops at the first occurrence of </code>. The parentheses create a capture group that you can access in the replacement logic.

Implementing Replacement Logic

Once you have the correct pattern, extracting the string is only half the battle. You also need to pull the matched content out of the parent string, perform operations on it, and then put it back. Using preg_match_all or simply iterating through matches is one approach, but for a single replacement scenario, preg_replace_callback is the most efficient tool. It allows you to define a closure that runs every time the regex matches, giving you full control over the captured data before re-inserting it into the string.

Here is how you structure that logic:

$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <code>Donec sed erat vel diam ultricies commodo. Nunc venenatis tellus eu quam suscipit quis fermentum dolor vehicula.</code>";

// Define the regex with a non-greedy capture group
$regex = '/<code>(.*?)<\/code>/';

$modifiedContent = preg_replace_callback($regex, function ($matches) {
    // $matches[0] is the full match including tags (<code>...</code>)
    // $matches[1] is the captured content without tags
    
    $originalContent = $matches[0];
    $extractedText = $matches[1];

    // Perform operations on the extracted text
    $processedText = strtoupper($extractedText); // Example operation

    return "<code>{$processedText}</code>";
}, $content);

echo $modifiedContent;

In this example, preg_replace_callback returns a new string where every instance of <code>...</code> has been replaced by the result of the closure. Inside the closure, $matches[1] holds the text you need to manipulate. You transform it (in this case, converting it to uppercase) and then return a string that reconstructs the original HTML tags around the new content.

Trade-offs and Considerations

While regex is powerful for parsing simple structures like this, it is important to remember its limitations. This solution works well for well-formed HTML where tags are not nested or malformed. If your content contains invalid HTML, such as a missing closing tag or escaped characters that break the pattern, preg_replace might fail or produce unexpected results.

For complex parsing tasks involving deeply nested structures or strict HTML validation, using a dedicated parser like DOMDocument is often safer. However, for straightforward text manipulation where performance matters and the HTML structure is predictable, the regex approach with a callback offers a clean, dependency-free solution without requiring external libraries.

Our network