在PHP中的字符串字符之间过滤

时间:2013-05-21 11:47:16

标签: php string split

我有一个这样的字符串:12PUM4

开头有两到三个数字,中间有三个字符,最后有一到两个数字。

我想将它分成三个部分:

  1. 字符前的数字
  2. 中间的人物
  3. 人物背后的其余部分。
  4. 有人可以帮忙吗?

5 个答案:

答案 0 :(得分:4)

您可以使用preg_match();

$str = '12PUM4';
$matches = array();
preg_match('/([0-9]+)([a-zA-z]+)(.*)/', $str, $matches);
print_r($matches);

<强>输出

Array ( [0] => 12PUM4 [1] => 12 [2] => PUM [3] => 4 )

当您使用此功能时,它将分割文本并将匹配放在$matches数组

  • [0-9]+ - 匹配数字至少一个或多个
  • [a-zA-Z]+是至少一个或多个字符
  • .*是(差不多)
  • () - 用作放置在$matches数组
  • 中的子模式

有关如何使用preg_match的更多信息,请访问here

substr()的解决方案,你写道它最终有12位数,3个字符和1或2位数。

$str = '12PUM4';
$matches = array( 0 => substr($str,0, 2), 1 => substr($str, 2, 3) , 2 => substr($str, 5, strlen($str)>6 ? 2 : 1));
print_r($matches);

<强>输出

Array ( [0] => 12 [1] => PUM [2] => 4 )

答案 1 :(得分:1)

sscanf()也可以作为选项:

$input = '12PUM4'; 
$splitValues = sscanf('%d%[A-Z]%d', $input); 
var_dump($splitValues);

答案 2 :(得分:0)

使用正则表达式

$string = '12PUM4';
$array = preg_split('#(?<=\D)(?=\d)|(?<=\d)(?=\D)#i', $string);

答案 3 :(得分:0)

试试这个

$name = "12PUM4"
$pattern = "/^([0-9]{2,3})([A-Z]{3})([0-9]{1,2})$/";
preg_match($pattern, $name , $matches);
echo $matches[1]; // first numbers
echo $matches[2]; // middle chars
echo $matches[3]; // last numbers

答案 4 :(得分:0)

$string = '12PUM4';

$strCnt = strlen($string);
$tmpStr = '';
$conArr = array();
for($i=0;$i<$strCnt;$i++){
    if(is_numeric($string[$i])){
        if($tmpStr != '' && !is_numeric($tmpStr)){
            $conArr[] = $tmpStr;
            $tmpStr = '';
        }
        $tmpStr .= $string[$i]; 
    }else{
        if(is_numeric($tmpStr)){
            $conArr[] = $tmpStr;
            $tmpStr = '';
        }
        $tmpStr .= $string[$i]; 
    }
}
$conArr[] = $tmpStr;

print_r($conArr);