Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

wordpress - Matching String Wrapped In Symbol For Regex Replace

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use

~~([sS]*?)~~(?!~)|~([^~]*)~

See the regex demo. Details:

  • ~~([sS]*?)~~(?!~) - ~~, 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('/~~([sS]*?)~~(?!~)|~([^~]*)~/', 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>.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...