Question

How can separate alphanumeric value with space in one statement

Example :

$arr="new stackoverflow 244code 7490script design"; 

So how can possible to separate alpha and number with space like :

$arr="new stackoverflow 244 code 7490 script design";
Was it helpful?

Solution 2

You may use preg_replace (Example):

$arr = "new stackoverflow 244code 7490script design"; 
$newstr = preg_replace('#(?<=\d)(?=[a-z])#i', ' ', $arr);
echo $newstr; // new stackoverflow 244 code 7490 script design

The regex pattern used from user1153551's answer.

OTHER TIPS

You can use preg_split() function

Check demo Codeviper

preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");

PHP

print_r(preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design"));

Result

Array ( [0] => new stackoverflow 244 [1] => code 7490 [2] => script design )

You can also use preg_replace() function

Check demo Codeviper

PHP

echo preg_replace('#(?<=\d)(?=[a-z])#i', ' ', "new stackoverflow 244code 7490script design");

Result

new stackoverflow 244 code 7490 script design

Hope this help you!

Use preg_replace like this:

$new = preg_replace('/(\d)([a-z])/i', "$1 $2", $arr);

regex101 demo

(\d) match and catches a digit. ([a-z]) matches and catches a letter. In the replace it puts back the digit, adds a space and puts back the letter.


If you don't want to use backreferences, you can use lookarounds:

$new = preg_replace('/(?<=\d)(?=[a-z])/i', ' ', $arr);

If you want to replace between letter and number as well...

$new = preg_replace('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', ' ', $arr);

regex101 demo

(?<=\d) is a positive lookbehind that makes sure that there is a digit before the current position.

(?=[a-z]) is a positive lookahead that makes sure that there is a letter right after the current position.

Similarly, (?<=[a-z]) makes sure there's a letter before the current position and (?=\d) makes sure there's a digit right after the current position.


An different alternative would be to split and join back with spaces:

$new_arr = preg_split('/(?<=\d)(?=[a-z])/i', $arr);
$new = implode(' ', $new_arr);

Or...

$new = implode(' ', preg_split('/(?<=\d)(?=[a-z])/i', $arr));

preg_split

preg_split — Split string by a regular expression

<?php

      // split the phrase by any number of commas or space characters,
     // which include " ", \r, \t, \n and \f

    $matches = preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");

    echo $matches['0'],' '.$matches['1'].' '.$matches['2'];



    ?>

WORKING DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top