PHP从字符串中拆分名称和数字

时间:2014-09-11 00:30:04

标签: php

我遇到将字符串拆分为名称=>的问题数字对应物一旦我有一个字符串,其中数字是字符串的一部分。

例如,我的函数将它们拆分为适当的名称=>值

Helium Isotopes 19,533      // Becomes Helium Isotopes => 19333
Strontium Clathrates    22  // Strontium Clathrates => 22

但是当它到达这个例子时

Fullerite-C540 300        // Fullerite-C => 540

它一直让我疯狂,试图找到一种方法让它忽略附在信上的数字

对此的任何帮助将不胜感激!

编辑:我的功能如下

splitNameNumber($str, ' ', ',');// Common usage is like this
function splitNameNumber($str, $dlm1, $dlm2) {
    $chars = array('.','(',')','[',']','<','>','?',"'",'^','*','-','+','\\','/');
    if(in_array($dlm1, $chars)) $dlm1 = '\\'.$dlm1;
    if(in_array($dlm2, $chars)) $dlm2 = '\\'.$dlm2;

    // gets an array with the 'Name-Number' sub-strings from $str
    if(preg_match_all('/([A-z \._\-'. $dlm1 . $dlm2. ']+[0-9]+)/i', $str, $mt)) {
        $re = array();              // variable for data to return
        $max_sub_strings = count($mt[0]);      // number of matched substrings

        // traverse the matched sub-strings
        for($i=0; $i<$max_sub_strings; $i++) {
            // gets separated the Name and Number, and adds them in $re array
            if(preg_match('/([a-z \._\-'. $dlm1. ']+)([0-9]+)/i', $mt[0][$i], $mt2)) {
                $re['name'][$i] = trim($mt2[1], ' '. $dlm1);
                $re['num'][$i] = $mt2[2];
            }
        }

        return $re;
    }
    else return false;
}

3 个答案:

答案 0 :(得分:1)

这看起来像是preg_split的工作:

$parts = preg_split('/\s+(?=\d)/', $line);
$value = (int) str_replace(',', '', array_pop($parts));
$name = implode(' ', $parts);

这将处理您问题中的所有示例,只需使用后跟数字的空格分割,使用分割的最后部分作为数字,并使用其余部分作为名称。

名称可以以数字开头,包含数字,以数字结尾,无论您需要什么。

答案 1 :(得分:-1)

我认为在这种情况下你可能想要使用正则表达式将这个字符串分成两部分;尚未包含任何数字的部分,其余部分以数字开头。考虑the following regex

/([^\d]+)[^\d.]*([\d\s]+)/

你的PHP实现:

$example = 'Fullerite-C540 300';

$pattern = '/([^\d]+)(.+)/';
preg_match($pattern, $example, $matches);

$joined = array($matches[1], $matches[2]);

示例输出:

Array (
    [Fullerite-C] => 540 300
)

答案 2 :(得分:-2)

考虑到你似乎正在寻找一个数字,寻找空间

$ro = preg_replace('/\s+/', ' ',$str); // Remove all the whitespace down to one space
$ro = explode(" ", $ro); // Explode into array looking for the space