Using PHP replace regex with regex

Using PHP replace regex with regex

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

Stefan Bogdanescu

Founder & Senior Architect

Using PHP replace regex with regex

Turning a plain string into hyperlinked hashtags requires a precise understanding of how regular expressions handle both matching and replacement. The goal is to transform #English into <a href="...">#English</a> while ensuring the anchor tag itself doesn't get interpreted as part of the hash match again. This specific pattern—matching text that includes special characters like #, letters, and then wrapping it in HTML—is a classic use case for PCRE's backreference capabilities within the replacement string.

In PHP, the standard approach involves preg_replace. You define a pattern that captures the content of the hashtag and then use a callback or a backreference to reconstruct the HTML during the substitution. The most robust method uses a capturing group around the hashtag content and references it in the replacement string using $1.

Here is a functional implementation:

$text = "any word here related to #English must #be replaced.";

// Pattern matches a hash followed by one or more word characters
$pattern = '/#([a-zA-Z0-9_]+)/';

// Replacement uses $1 to refer to the captured group (the text after #)
// This ensures the hashtag content appears exactly as matched inside the anchor tag
$replacement = '<a href="bla bla">$1</a>';

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

echo $result;

This outputs: any word here related to <a href="bla bla">#English</a> must <a href="bla bla">#be</a> replaced.

The logic here is straightforward. The regex /#([a-zA-Z0-9_]+)/ explicitly targets the hash symbol followed by alphanumeric characters and underscores. By placing the hashtag content inside parentheses (...), we create a capturing group. When the engine finds a match, it replaces the entire string (including the original #) with the replacement template. The $1 placeholder tells PHP to insert the exact text that matched inside the first set of parentheses.

A critical pitfall in this scenario is modifying the pattern or replacement incorrectly. If you were to try and use a callback function instead, such as preg_replace_callback, it offers more flexibility but adds complexity for a simple transformation. With callbacks, you receive an array of matches and must manually construct the HTML string, which increases the risk of typos in the link attributes or forgetting to sanitize input if the hashtag content comes from user data.

Another consideration is the scope of what constitutes a valid hashtag character. The pattern [a-zA-Z0-9_] restricts matching to standard alphanumeric characters and underscores. In social media contexts, hashtags often include numbers and sometimes apostrophes depending on platform rules. If your requirements are looser, you might adjust the character class to [^\s]+ (match anything except whitespace), though this risks capturing punctuation that shouldn't be part of the link text.

Performance is generally not an issue with preg_replace unless you are processing millions of strings in a tight loop, where compiling the pattern outside the loop becomes essential. However, readability remains a trade-off. While preg_replace is concise, using named groups like /(?P<hash>#)(?<content>[a-zA-Z0-9_]+)/ can make the replacement string more readable if you need to reference specific parts by name rather than index.

The solution relies entirely on PHP's PCRE support. If your environment is older or lacks these extensions, standard eregi_replace won't handle backreferences in the replacement string, rendering this approach impossible without switching libraries. For modern PHP versions (7.4+), this pattern is efficient and safe provided you validate that the resulting HTML will be rendered in a context where special characters are escaped appropriately to prevent XSS vulnerabilities if the link destination or content originates from untrusted sources.

Our network