2013-01-15 28 views
3

我有一些字符串,可以采用以下格式字符串分割到文本和数字

 
sometext moretext 01 text 
text sometext moretext 002 
text text 1 (somemoretext) 
etc

我想这些字符串分成如下:数量和数量

例如前文:文本的文本1(somemoretext)
当拆分将输出:
文本=文本文本
数= 1

任何后面的数字可以被丢弃

读到了有关使用正则表达式,也许使用的preg_match或使preg_split,但我失去了当谈到正则表达式部分

回答

10
preg_match('/[^\d]+/', $string, $textMatch); 
preg_match('/\d+/', $string, $numMatch); 

$text = $textMatch[0]; 
$num = $numMatch[0]; 

或者,你可以使用preg_match_all与捕捉组做这一切在一杆:

preg_match_all('/^([^\d]+)(\d+)/', $string, $match); 

$text = $match[1][0]; 
$num = $match[2][0]; 
+0

谢谢你的快速答复。没有意识到这很容易。 – user1981823

+2

@ user1981823 - 一旦你知道如何去做,一切都很简单;) –

+0

值得注意的是,在你的例子** A **中,输出仍然是数组,所以'$ textMatch [0] [0] = string'。此外,您的链接不再有效。 – Martin

1

使用preg_match_all() +如果你希望马TCH每行使用m modifier

$string = 'sometext moretext 01 text 
text sometext moretext 002 
text text 1 (somemoretext) 
etc'; 
preg_match_all('~^(.*?)(\d+)~m', $string, $matches); 

所有结果都在$matches阵列,它看起来像这样:

Array 
(
    [0] => Array 
     (
      [0] => sometext moretext 01 
      [1] => text sometext moretext 002 
      [2] => text text 1 
     ) 
    [1] => Array 
     (
      [0] => sometext moretext 
      [1] => text sometext moretext 
      [2] => text text 
     ) 
    [2] => Array 
     (
      [0] => 01 
      [1] => 002 
      [2] => 1 
     ) 
) 

输出例如:

foreach ($matches[1] as $k => $text) { 
    $int = $matches[2][$k]; 
    echo "$text => $int\n"; 
}