Add space before and after a number

Viewed 864

I'm trying to add a space before and after any number in a string. For example, if I have JS35BX54NV33, I will get JS 35 BX 54 NV 33

I'm using this:

preg_replace("/(\\d)([a-z])/i", "$1 $2", $mystring)

But it only add space AFTER each number.

Thanks for your help!

2 Answers

Find the zero-width positions where you wish to inject spaces using lookarounds. No capture groups are necessary.

  • \d matches a numeric character.
  • \D matches a non-numeric character.
  • (?<=...) looks behind.
  • (?=...) looks ahead.

Code: (Demo)

$mystring = 'JS35BX54NV33';
var_export(preg_replace('/(?<=\D)(?=\d)|(?<=\d)(?=\D)/', ' ', $mystring));

Output:

'JS 35 BX 54 NV 33'

var_export() is used to reveal that there are no leading or trailing spaces generated.

Related