0

I have the following string: 01SOMECOMPANY and I want to end up with 01 SOMECOMPANY. How do I do this using regular expressions?

2
  • Have you tried anything at all? Commented Apr 17, 2013 at 19:19
  • You don't need regex to inset a space at index = 2. A better explanation and some more use cases would help your cause. Commented Apr 17, 2013 at 19:19

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Both work, you canfind this here in the manual: php.net/preg_replace - see the replacement parameter.
0

A regex could look something like this:

  (\d+)([a-zA-Z]+)

You could then use the capturing groups in the replacement expression, with a space between them.

  $1 $2

Comments

0

The following example will explain to you.

$string = "01SOMECOMPANY";
preg_match('/^([0-9]*)(.*)/i', $string, $matches);
echo $matches[1]." ".$matches[2];

The result:
01 SOMECOMPANY

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.