2017-03-04 95 views
1

我有一个包含这样的记数的字符串:PHP - 转换包含特定记数字符串转换成一个数组

$string = '01. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again'; 

现在我想这个字符串(没有任何中断)转换含有这种记数到包含这些项目的数组(“只是一个例子”,“另一个例子”,“另一个例子”等)。

我不能”只使用

$array = explode('.', $string); 

,因为这些项目还可以包含圆点等符号或数字就像在我所谓的‘Example.mp3’第四个项目。在记数上升到约50%,但项目的量是不一样的,每次(有时我只有一个项目,但有时我在这串2,3甚至15个项目)。它并不总是以一个0

我怎样才能“转换”这个字符串到一个数组,而不使用点作为分隔符,但也许使用这整个numberation格式和点一起作为分隔符?

回答

0

这绝对不是最好的解决方案成为可能,但据我可以告诉它几乎可以处理任何输入相当不错。

<?php 
    $string = '01. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again'; 

    $things=explode(' ',$string); 
    $num=1; 

    $your_output=array(); 

    foreach($things as $thing) 
    { 
      $num_padded = str_pad($num, 2, '0', STR_PAD_LEFT) .'.'; 
      if($num_padded==$thing) 
      { 
        $num++; 
        $your_output[$num]=''; 
      } 
      else 
        $your_output[$num].=' ' . $thing; 

    } 

    $final_result=array(); 
    foreach($your_output as $k=>$v) 
    { 
      $final_result[]=trim($v); 
    } 

    var_dump($final_result); 

    ?> 
+0

非常感谢您的快速回答,您的解决方案完美无缺! :) –

0

这里是另一个选项,我也从第一个数字中删除了0。

$string = '1. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again'; 
// Replace the digit format with an easy delimiter 
$string_rep = preg_replace('/(\d{1,}\.\s?)/', '|', $string); 
// convert string to an array 
$string_arr = explode('|', $string_rep); 
// remove empty array entries 
$clean = array_filter($string_arr); 

print_r($clean); 

/* 
// result 
Array 
(
    [1] => Just an example 
    [2] => Another example 
    [3] => Just another example 
    [4] => Example.mp3 
    [5] => Test 123 
    [6] => Just an example again 
) 
*/