selfclose
selfclose

Reputation: 121

Regex: Replace After first space with   in php

I'm making translateModel in PHP, It's will be return out in HTML

So, In Example code it just replace space with ' '

preg_replace('/\s/', ' ', $myString);

But what I want is Replace After first space to so on (Not count first space)

Such as:

Upvotes: 1

Views: 336

Answers (2)

selfclose
selfclose

Reputation: 121

I think I found the answer:

preg_replace('/\s(?=\s)/', ' ', $myString);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

To replace each whitespace in a streak of whitespaces excluding the first whitespace, use

preg_replace('~(?<=\s)\s~', '&nbsp;', $myString)

See the regex demo.

It will turn A B C D E into A B C &nbsp;&nbsp;D &nbsp;&nbsp;&nbsp;&nbsp;E.

Your /\s(?=\s)/ lookahead solution will replace all whitespaces but the last one in a streak of whitespaces, as the positive lookahead requires the presence of the pattern immediately to the right of the current location, whole the lookbehind will look for a match to the left of the current location.

Upvotes: 1

Related Questions