GRowing
GRowing

Reputation: 4717

preg_replace pattern replacement versus single character?

I am using this line to replace a silly string with this ^_^ pattern

$newText = trim(preg_replace('/\^_^+/', "\r\n", $newText));

The patterns can be like this or multiples of the same ...

^_^ OR ^_^^_^ or ^_^^_^^_^

I am not exactly the king of regular expressions,, can someone help me understand how to replace a string versus a single character?

It works when I want to replace a single string or multiples of the same like this ^ for example..

$newText = trim(preg_replace('/\^+/', "\r\n", $newText));

I tried this and other similar combinations with no luck

preg_replace('/\^_\^+/', "\r\n", $newText)

Upvotes: 1

Views: 81

Answers (1)

elixenide
elixenide

Reputation: 44833

You need to escape both ^s and wrap \^_\^ in parentheses:

$newText = trim(preg_replace('/(\^_\^)+/', "\r\n", $newText));

Upvotes: 3

Related Questions