thiebo
thiebo

Reputation: 1435

preg_replace not replacing certain matching strings

I want to put a + in front of each word in a string, except when the word begins with a *.

Here's what I do to put the + in front of each word :

$string = "    *these are my words   ";
$trimmed = trim($string);
$pattern = '/ /';
$string2 = preg_replace ($pattern, ' +',$trimmed);

How do I avoid preg_replace to put a + in front of each word if that word has a * ?

Thanks

Upvotes: 1

Views: 1274

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174736

You could try the below negative lookbehind based regex.

preg_replace('~(?<!\S)([^*\s])~', '+\1', $str);
  • (?<!\S) Matches all the boundaries which exists at the start of each word. Here word means one or more non-space characters.

  • ([^*\s]) Matches a single character exists next to the matched boundary which must not be a space character or * symbol.

  • Now it replaces the matched chars with the + plus the chars present inside the first captured group.

DEMO

OR

preg_replace('~(^|\s)([^*\s])~', '\1+\2', $str);

DEMO

Upvotes: 1

Related Questions