1

I want to extract character and number from a alphanumeric value

For example 300G I want extract 300 and G as different values 500M : want to 500 and M Please help

4

6 回答 6

2

Try with preg_match:

$input = '300G';
preg_match('/(\d+)(\w)/', $input, $matches);

var_dump($matches);

Output:

array (size=3)
  0 => string '300G' (length=4)
  1 => string '300' (length=3)
  2 => string 'G' (length=1)

And extra:

list(, $digits, $letter) = $matches;
于 2013-07-08T11:01:04.583 回答
2

This code should do the trick.

$str = '300G';

preg_match("/(\d+)(.)/", $str, $matches);

$number = $matches[1];
$character = $matches[2];

echo $number; // 300
echo $character; // G
于 2013-07-08T11:04:08.823 回答
0
$input = '300G';
$number = substr($input, 0, -1);
$letter = substr($input, -1);
于 2013-07-08T11:01:23.937 回答
0

use a regular expression

   $regexp = "/([0-9]+)([A-Z]+)/";
   $string = "300G";

   preg_match($regexp, $string, $matches);

   print_r($matches);

$matches[1] = 300 $matches[2] = G

于 2013-07-08T11:02:05.307 回答
0
$pattern = '#([a-z]+)([\d]+)#i';
if (preg_match($pattern, $str, $matches)){
    $letters = $matches[1];
    $numbers = $matches[2];
}
于 2013-07-08T11:03:15.300 回答
0

Try this,

<?php
    $input = '300G';
    preg_match('/(\d+)(\w)/', $input, $matches);
    var_dump($matches);
?>
于 2013-07-08T11:04:21.277 回答