Home > Software design >  How to modify a word in a sentence using regex to find the word in php
How to modify a word in a sentence using regex to find the word in php

Time:11-28

I have a sentence with words/equations in it that start and end with $. For example,

"The $girl$ is a $good$ person"

I want to modify the sentence to

"The $$girl$$ is a $$good$$ person".

I have found a way to find the words but how to replace them with the modified version of themselves is the issue. I found this on this platform but it doesn't answer the question.

preg_replace('/\$\S \$/', '', $text) 

Any help will be appreciated. Thanks

CodePudding user response:

You can use

$text = 'The $girl$ is a $good$ person';
echo preg_replace('/\$[^\s$] \$/', '\$$0\$', $text);
// => The $$girl$$ is a $$good$$ person

See the PHP demo. See this regex demo. Details:

  • \$ - a $ literal char
  • [^\s$] - any one or more chars other than $ and whitespace
  • \$ - a $ literal char.

The \$$0\$ replacement means the whole match is replaced with itself ($0) and two $ are added on both ends.

To avoid re-wrapping $$...$$ substrings, you can use

$text = 'The $girl$ is a $good$ person, and keep $$this$$.';
echo preg_replace('/\${2,}[^\s$] \${2,}(*SKIP)(*FAIL)|\$[^\s$] \$/', '\$$0\$', $text);
// => The $$girl$$ is a $$good$$ person, and keep $$this$$.

See this PHP demo. The \${2,}[^\s$] \${2,}(*SKIP)(*FAIL)| part matches all substrings not containing $ and whitespace between two or more $ chars and skips them.

See the regex demo.

CodePudding user response:

You can assert whitespace boundaries around the pattern and use the full match using $0 around dollar signs.

Note that \S can also match $ so you could use a negated character class [^$] to match any character except the $

(?<!\S)\$[^$] \$(?!\S)
  • (?<!\S) Assert a whitespace boundary to the left
  • \$ Match $
  • [^$] Match 1 occurrences of any char except $
  • \$ Match $
  • (?!\S) Assert a whitespace boundary to the right

See a regex demo and a PHP demo.

$text = '"The $girl$ is a $good$ person"';
echo preg_replace('/(?<!\S)\$[^$] \$(?!\S)/', '$$0$', $text);

Output

The $$girl$$ is a $$good$$ person
  • Related