English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Using PHP, how can I split a string like this, LB100A, into something like this, LB 100 A? I will end up having 100's of strings similiar to this that will vary in letters and numbers so I can't really use a position function and I won't know the delimiter so I can't use explode(). I'm guessing regular expressions will do this but I'm not sure how to go about it.

Thanks.

2006-09-08 08:08:02 · 2 answers · asked by rob 3 in Computers & Internet Programming & Design

2 answers

You need to go through the string and test each character with is_numeric():

function separate_numbers_from_letters ($string) {
$parts = array(0 => $string{0});
$part = 0;
$n = strlen($string);
$flag = is_numeric($string{0});
for ($i = 1; $i < $n; $i++) {
if (is_numeric($string{$i}) == $flag) {
$parts[$part] .= $string{$i};
} else {
$flag = !$flag;
$part++;
array_push($parts, $string{$i});
}
}
return $parts;
}

Calling separate_numbers_from_letters ('LB100A') would return:

Array
(
[0] => LB
[1] => 100
[2] => A
)

2006-09-11 05:04:48 · answer #1 · answered by NC 7 · 0 0

If every string is going to be in the form of XXYYZ then it's fairly simple.

$string = "LB100A";

$x = substr($string, 0, 2);
$y = substr($string, 2, 2);
$z = substr($string, 4, 2);

Then you have $x, $y, $z equal the various chunks.

You may have to tweak the numbers as this is out of my head and I haven't tested it.

substr() returns the portion of string ($string) specified by the start (the first number) and length (second number. the number is the number of characters to retrieve) parameters.

You could do a complex regular expression and all that but this is the simplest way if the strings are always in the same format.

2006-09-08 11:12:41 · answer #2 · answered by lordfish 1 · 0 0

fedest.com, questions and answers