I am partially disabled. I write a LOT of wordpress posts in ‘text’ mode and to save typing I will use a shorthand for emphasis and strong tags. Eg. I’ll write -this-
for <em>this</em>
.
I want to add a function in wordpress to regex replace word(s) that have a pair of dashes with the appropriate html tag. For starters I’d like to replace -this-
with <em>this</em>
Eg:
-this-
becomes <em>this</em>
-this-.
becomes <em>this</em>.
What I can’t figure out is how to replace the bounding chars. I want it to match the string, but then retain the chars immediately before and after.
$pattern = '/s-(.*?)-(s|.)/';
$replacement = '<em>$1</em>';
return preg_replace($pattern, $replacement, $content);
…this does the ‘search’ OK, but it can’t get me the space or period after.
Edit: The reason for wanting a space as the beginning boundary and then a space OR a period OR a comma OR a semi-colon as the ending boundary is to prevent problems with truly hyphenated words.
So pseudocode:
1. find the space + string + (space or punctuation)
2. replace with space + open_htmltag + string + close_htmltag + whatever the next char is.
Ideas?
You can try with capturing groups with
<em>$1</em>$2
as substitution.DEMO
sample code:
Note: Use single space instead of
s
that match any white space character[rntf ]
Edited by o/p: Did not need opening space as delimiter. This is the winning answer.
You can try with Positive Lookahead as well with only single capturing group.
substitution string:
<em>$1</em>
DEMO
You can use this regex:
Check the substitution section:
Working demo
Edit: as an improvement you can also use
-(.*?)-
and utilize capturing group1
In the code below, the regex pattern will start at a hyphen and collect any non-hyphen characters until the next hyphen occurs. It then wraps the collected text in an
em
tag. The hyphens are discarded.Note: If you use a hyphen for its intended purposes, this may cause problems. You may want to devise an escape character for that.
Result: