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


How to extract character and number from alphanumeric value using php

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

例如300G,我希望提取300G作为不同的值500M:想要500和M请帮助

这段代码应该可以完成任务。

$str = '300G';
preg_match("/('d+)(.)/", $str, $matches);
$number = $matches[1];
$character = $matches[2];
echo $number; // 300
echo $character; // G

试用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;
$input = '300G';
$number = substr($input, 0, -1);
$letter = substr($input, -1);

使用正则表达式

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

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

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

试试这个,

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