questions

Matching String Wrapped In Symbol For Regex Replace

Rate this post

I’m trying to figure out how to implement Regex on my WordPress blog.

The Problem

I’d like to replace certain content with some inline styles, and I’m using Regex to accomplish this.

My idea is as follows: find the string wrapped in a particular symbol, i.e. “~string~” and dynamically replace this with a span that has a particular class.

I’m going for a similar effect to SO’s inline code highlighting feature, but instead of using backticks, I’m using “~” as my symbol of choice (since WordPress already identifies “`” as code).

Quick Example

Original Text

This is a demo paragraph with a wrapped string ~here~, with another string ~~here~~.

After Regex Replacement

This is a demo paragraph with a wrapped string <span class="classOne">here</span>, with another string <span class="classTwo">here</span>.

What I’m Struggling With

The regex I’m using is this: /~(.*?)~/, and it’s working fine for finding strings such as “~demo~”, but I’m not sure how to extend it to be able to find strings with multiple delimiters, like: “~~demo~~”.

The tricky part for me is that it needs to distinguish between just one “~” versus two of them because I’d like to assign different replacements to each result.

Any help would be appreciated! Thanks in advance.

 

✔️Solution:

You can use

~~([\s\S]*?)~~(?!~)|~([^~]*)~

See the regex demo. Details:

  • ~~([\s\S]*?)~~(?!~)~~, then a capturing group #1 matching any zero or more chars but as few as possible, and then a ~~ substring not followed with another ~ char
  • | – or
  • ~([^~]*)~ – a ~, then a capturing group #2 matching zero or more chars other than ~, and then a ~

If you use it in PHP, you may use the pattern with preg_replace_callback where you may define separate replacement logic when a specific capturing group is matched.

See a PHP demo:

$html = 'This is a demo paragraph with a wrapped string ~here~, with another string ~~here~~.';
echo preg_replace_callback('/~~([\s\S]*?)~~(?!~)|~([^~]*)~/', function ($m) {
    return !empty($m[1]) ? '<span class="classTwo">' . $m[1] . '</span>' : '<span class="classOne">' . $m[2] . '</span>';
},$html);
// => This is a demo paragraph with a wrapped string <span class="classOne">here</span>, with another string <span class="classTwo">here</span>.

Leave a Reply

Your email address will not be published.

Back to top button