2012-08-25 37 views
0

我有以下字符串:获取文本和数字

Some random 516 text100. 
text3. 

我怎么能编程方式获取类似:

$a[0]["text"] = Some random 516 text 
$a[0]["id"] = 100 

$a[1]["text"] = text 
$a[1]["id"] = 3 

感谢

+1

这太糟糕了,你没有 “一些随机的516文,100” 和 “文本3”!那么它只是在分裂字符串。 –

+0

它总是以“text {NumberID}”结尾?如果是这样,那么它可以做到,让我知道 – RedhopIT

+0

你可以使用像@GlaciesofPacis分隔符带来了吗?否则,你将不得不使用正则表达式... – jeremy

回答

3

这工作:

$input = array("Some random 516 text100.", 
     "text3."); 

$output=array(); 

foreach ($input as $text) { 
    preg_match('/(.*?)(\d+)\./',$text,$match); 
    array_shift($match); // removes first element 
    array_push($output,$match); 
} 

print_r($output); 

输出:

Array 
(
    [0] => Array 
     (
      [0] => Some random 516 text 
      [1] => 100 
     ) 

    [1] => Array 
     (
      [0] => text 
      [1] => 3 
     ) 

) 
2

如果你输入这个规则,你可以使用正则表达式。

注:这个版本需要.text<number>部分下,您可能需要这取决于你的输入来调整:

$in='Some random 516 text100. 
text3.'; 

preg_match_all('/^(?<text>.*?text)(?<id>\d+)\./im', $in, $m); 
$out = array(); 
foreach ($m['id'] as $i => $id) { 
    $out[] = array('id' => $id, 'text' => $m['text'][$i]); 
} 
var_export($out); 

在foreach按摩,结果到请求的格式,你可能不需要如果你可以使用原来的preg_match_all()返回。