Insert character before and after of character but ignore space between two characters

Viewed 63

How can I insert the character before and after in a character but ignore whitespace between two character or more.

I try this regex but it's return incorrectly

$str = "        echo '<pre>';";
$replaces = preg_replace('/(\S{3,})/', '[:$1:]',$str);
var_dump($replaces);

But it's return this following

        [:echo:] [:'<pre>';:]

What I want is this

        [:echo '<pre>';:]

Thanks in advance

1 Answers

You can use either of

preg_replace('~\S{3,}(?:\s\S{3,})*~', '[:$0:]', $str)?
preg_replace('~\S+(?:\s\S+)*~', '[:$0:]', $str)?

See the regex demo. The \S{3,} matches three or more consecutive non-whitespace chars while \S+ matches one or more of these chars.

Note you do not need to enclose the whole match with a capturing group, you may use $0 in the replacement pattern to refer to the whole match.

Related