如何使用php从字母数字值中提取字符和数字

时间:2013-07-08 10:58:55

标签: php

我想从字母数字值中提取字符和数字

例如300G我想要提取300G作为不同的值 500M:想要500和M. 请帮忙

6 个答案:

答案 0 :(得分:1)

尝试preg_match

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

var_dump($matches);

输出:

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

额外的:

list(, $digits, $letter) = $matches;

答案 1 :(得分:1)

这段代码可以解决问题。

$str = '300G';

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

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

echo $number; // 300
echo $character; // G

答案 2 :(得分:0)

$input = '300G';
$number = substr($input, 0, -1);
$letter = substr($input, -1);

答案 3 :(得分:0)

使用正则表达式

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

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

   print_r($matches);

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

答案 4 :(得分:0)

$pattern = '#([a-z]+)([\d]+)#i';
if (preg_match($pattern, $str, $matches)){
    $letters = $matches[1];
    $numbers = $matches[2];
}

答案 5 :(得分:0)

试试这个,

<?php
    $input = '300G';
    preg_match('/(\d+)(\w)/', $input, $matches);
    var_dump($matches);
?>