Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/66062492/insert-character-before-and-after-of-character-but-ignore-space-between-two-char

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use either of

preg_replace('~S{3,}(?:sS{3,})*~', '[:$0:]', $str)?
preg_replace('~S+(?:sS+)*~', '[:$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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...