Replace each character of matched text with certain text

Viewed 58

I use PCRE regex and I have a problem with replacing each word of the matched text.

I use this pattern to match the desired text with grouping:

(?<=^|[_\-/:]\w)(\w+?)(?=\w[_\-/:]|$)

And the sample text is this:

yVOdbtnRWSkpgi0iDWeRtyynyREV7yVKyNuJmsFmpSPtnlXaLb/Ik4zuyJFwqRWCGeIRp7m3Cef9kSjvCIrFG4iaweaB49WecZoNP8CTta79kVXpAcIVohHnsLcJ5+

I would like to convert all characters of grouped match ($1) to ?i:

yV?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?iLb/Ik?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?i?iJ5+

How can I do this?

1 Answers

You may use this regex to search:

~(?<=[^+/_-]\w)\w(?=\w[^+/_-])~

and replace using:

?i

RegEx Demo

Code:

$repl = preg_replace('~(?<=[^+/_-]\w)\w(?=\w[^+/_-])~', '?i', $str);

RegEx Demo

  • (?<=[^+/_-]\w): Positive lookbehind to assert that we have a character that is not a +, /, _ and - followed by a word character followed by at previous position
  • \w: Match a word character
  • (?=\w[^+/_-]): Positive lookahead to assert that we have a word character followed by a character that is not a +, /, _ and - ahead
Related