Reputation: 1054
I have following regex:
// Before: "Foo Bar Test";
$str = preg_replace( "/(^| )(\w)/", '$1+$2', $str );
// After: "+Foo +Bar +Test";
Is it possible to add the char "*" at the end of every word?
The result I am looking for is:
// +Foo* +Bar* +Test*
Is it possible to do it in the same regex? Or do I have to use a new one?
Upvotes: 1
Views: 75
Reputation: 785276
You can do:
$str = preg_replace( "/(^| )(\w+)\b/", '$1+$2*', $str );
echo "$str\n";
//=> +Foo* +Bar* +Test*
Making 2nd captured group as (\w+)
will make it capture full word and putting *
after $2
will place *
at right place.
PS: You can also use lookbehind assertion:
$str = preg_replace( "/(?<= |^)(\w+)\b/", '+$1*', $str );
to get the same output.
Upvotes: 3