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";
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.
You can use preg_split() function
Check demo Codeviper
preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design"));
Array ( [0] => new stackoverflow 244 [1] => code 7490 [2] => script design )
You can also use preg_replace() function
Check demo Codeviper
echo preg_replace('#(?<=\d)(?=[a-z])#i', ' ', "new stackoverflow 244code 7490script design");
new stackoverflow 244 code 7490 script design
Hope this help you!
preg_split — Split string by a regular expression
<?php
// split the phrase by any number of commas or space characters,
// which include " ", , \t,
and \f
$matches = preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");
echo $matches['0'],' '.$matches['1'].' '.$matches['2'];
?>
Use preg_replace
like this:
$new = preg_replace('/(\d)([a-z])/i', "$1 $2", $arr);
(\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);
(?<=\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));