I have the following string: 01SOMECOMPANY and I want to end up with 01 SOMECOMPANY. How do I do this using regular expressions?
4 Answers
regular expression would be "/^([0-9]+)(.+)/" and the replacement "\1 \2" or "$1 $2". Can't remember if PHP uses \1 or $1 to refer the first match in regexp.
1 Comment
I used preg_split function to separate components of the string. And then joined the elements, using space as a separator:
<?php
$str = '01string44str';
$elements = preg_split('/(\d+)/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$output = implode(" ", $elements);
print $output;
This prints:
01 string 44 str
More effective solution will be using preg_replace function with a back reference:
<?php
$str = '01string44str';
$output = preg_replace('/(\d+)/', '$1 ', $str);
print $output;
This prints a little different result:
01 string44 str
Not sure, whether you need a space between 'string' and '44'. For your string '01SOMECOMPANY' it works correctly though.
index = 2. A better explanation and some more use cases would help your cause.