1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.