2013-04-05 56 views
1

我想通過查找PHP標籤來拆分帶換行符的字符串。需要通過查找PHP標籤來拆分帶換行符的字符串

這裏是我的代碼,我到目前爲止有:

$contents = ' 
some test 
some more test 
test 1 
<?php 
test 2 and test 4 
test 6 
?> 
test 7 
test 9 
<?php 
test 10 
test 12 
>? 
test 13 
<?php test 14 
test 16 
?> 
test 17 
'; 

正如你所知道的,PHP代碼是偶的測試實例,和ODD測試的例子是PHP標籤外面。

我所希望做的是提取到一個數組的PHP代碼每次迭代:

預期結果:

array(
    [0] => <?php 
      test 2 and test 4 
      test 6 
      ?> 

    [1] => <?php 
      test 10 
      test 12 
      >? 

    [2] => <?php test 14 
      test 16 
      ?> 
) 

我試圖與preg_split由結束標記,然後通過捕獲$explode[1]期初標籤,但我的代碼是錯誤的...

$ends = preg_split("/[?>]/s", $contents, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE); 
print_r($ends); 
foreach($ends as $flufcode){ 
    $trimcode = explode('<?php', $flufcode); 
    echo $trimcode . " next:"; 
} 

到目前爲止,我preg_split不工作,我相信我的[R斷行後egex不掃描。

+0

In line「test 12>?」你有一個synatx錯誤。它必須是 「測試12?」「我認爲 – Kingalione 2013-04-05 01:16:57

回答

1

您的示例代碼是錯誤的。無論如何,錯誤的預期結果。而像<?php echo '?>'; ?>這樣的正則表達式解析代碼將會失敗。

爲了正確和簡單的解析,您應該使用token_get_all。爲你舉例。

$tokens = token_get_all($contents); 

$catch = false; 
$codes = array(); 
$index = 0; 
foreach ($tokens as $token) 
    { 
    if (is_array($token) && $token[0] == \T_OPEN_TAG) 
     { 
     $catch = true; 
     $index++; 
     $codes[$index] = ''; 
     } 
    if ($catch) 
     $codes[$index] .= is_array($token) ? $token[1] : $token; 

    if (is_array($token) && $token[0] == \T_CLOSE_TAG) 
     { 
     $catch = false; 
     } 
    } 

var_export($codes); 

將產生與您提供的數據。

array (
    1 => '<?php 
test 2 and test 4 
test 6 
?> 
', 
    2 => '<?php 
test 10 
test 12 
>? 
test 13 
<?php test 14 
test 16 
?> 
', 
) 
+0

你做到了。我沒有完全理解這些功能,但我可以使用你的代碼。謝謝! – user1955162 2013-04-05 02:01:51

0

問號是一個正則表達式元字符 - 嘗試逃脫它:

$ends = preg_split("/\\?>/sm", $contents, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE); 
+0

結果是一樣的嗎? $ ends是一個包含[0]中全部內容的數組。 – user1955162 2013-04-05 01:18:05

0

我會用

preg_match_all("/<\?php.*?\?>/s", $contents, $matches); 

這捕獲<?php?>之間的一切不情願地(不貪婪)。請注意,$matches數組將被嵌套。

相關問題