2013-07-20 34 views
0

我想從一個字符串中分組一堆文本併爲它創建一個數組。如何在PHP中處理複雜的字符串?

的字符串是這樣的:

<em>string</em> and the <em>test</em> here. 
tableBegin rowNumber:2, columnNumber:2 11 22 33 44 tableEnd 
<em>end</em> text here 

我希望得到一個數組像下面這樣的結果

array (0 => '<em>string</em> and the <em>test</em> here.', 
     1=>'rowNumber:5', 
     2=>'columnNumber:3', 
     3=>'11', 
     4=>'22', 
     5=>'33', 
     6=>'44' 
     7=>'<em>end</em> text here') 

11,22,33,44在用戶進入table單元格數據。我想讓他們有獨特的index,但保留其餘的文本在一起。

tableBegintableEnd只是爲table cell數據

任何幫助或提示的支票?非常感謝!

+0

你的問題不太清楚。有一些文本留在你的第一塊文本中,而不是注入到你的數組列表中 – samayo

+0

你可以使用Regex來解決這個問題。儘管想出一個功能性的東西太遲了。 – silkfire

+0

@Simon_eQ tableBeing和tableEnd只是對字符串的檢查。我認爲這將有助於添加它們。我不希望他們進入陣列。 – FlyingCat

回答

2

您可以嘗試以下操作,注意您需要PHP 5。3+:

$string = '<em>string</em> and the <em>test</em> here. 
tableBegin rowNumber:2, columnNumber:2 11 22 33 44 tableEnd 
SOme other text 
tableBegin rowNumber:3, columnNumber:3 11 22 33 44 55 tableEnd 
<em>end</em> text here'; 

$array = array(); 
preg_replace_callback('#tableBegin\s*(.*?)\s*tableEnd\s*|.*?(?=tableBegin|$)#s', function($m)use(&$array){ 
    if(isset($m[1])){ // If group 1 exists, which means if the table is matched 
     $array = array_merge($array, preg_split('#[\s,]+#s', $m[1])); // add the splitted string to the array 
     // split by one or more whitespace or comma --^ 
    }else{// Else just add everything that's matched 
     if(!empty($m[0])){ 
      $array[] = $m[0]; 
     } 
    } 
}, $string); 
print_r($array); 

輸出

Array 
(
    [0] => string and the test here. 

    [1] => rowNumber:2 
    [2] => columnNumber:2 
    [3] => 11 
    [4] => 22 
    [5] => 33 
    [6] => 44 
    [7] => SOme other text 

    [8] => rowNumber:3 
    [9] => columnNumber:3 
    [10] => 11 
    [11] => 22 
    [12] => 33 
    [13] => 44 
    [14] => 55 
    [15] => end text here 
) 

正則表達式的解釋

  • tableBegin:匹配tableBegin
  • \s*:匹配空白零次或多次
  • (.*?):百搭ungreedy並把它放在第1組
  • \s*:匹配一個空格零次或多次
  • tableEnd:匹配tableEnd
  • \s*:匹配一個空格零次或多次
  • |:或
  • .*?(?=tableBegin|$):匹配一切直到tableBegin或線
  • s modifi結束呃:讓點也匹配換行
1

如果你找不到正則表達式專家,這是一個醜陋的做法。

所以,這是你的文字

$string = "<em>string</em> and the <em>test</em> here. 
tableBegin rowNumber:2, columnNumber:2 11 22 33 44 tableEnd 
<em>end</em> text here"; 

這是我的代碼

$E = explode(' ', $string); 
$A = $E[0].$E[1].$E[2].$E[3].$E[4].$E[5]; 
$B = $E[17].$E[18].$E[19]; 
$All = [$A, $E[8],$E[9], $E[11], $E[12], $E[13], $E[14], $B]; 

print_r($All); 

這是輸出

Array 
(
    [0] => stringandthetesthere. 
    [1] => rowNumber:2, 
    [2] => columnNumber:2 
    [3] => 11 
    [4] => 22 
    [5] => 33 
    [6] => 44 
    [7] => endtexthere 
) 

off-course,<em>標記將不可見,除非查看源代碼。

+0

RegEx是更好的答案,但我把你的aproach以及使用'explode's。這是我的版本:http://codepad.org/iSWnWSPm – DACrosby