2016-05-17 44 views
0

我期待從分隔符中提取php中的內容。例如:如何從分隔符中提取內容在PHP

content useless 
<---------> 
Content to get 
content to get 
content to get 
<---------> 
content useles 
content useless 
<---------> 
Content to get 
content to get 
content to get 
<---------> 
content useless 
<---------> 
Content to get 
content to get 
content to get 
<---------> 

現在我只有這個:

<?php 
$myfile = file_get_contents("foo.txt"); 
$rows = explode("\n", $myfile); 

foreach($row as $line => $data) { 
    if ($data == "<--------->") { 

    } 
} 
?> 

我真的不知道如何找到我的分隔符的第二位置,並檢索內容。

我希望我明白了! 問候和感謝。

+0

Beggining /結束? –

+0

例如是或其他 –

+0

將始終在<--------->之間?和多少可能的塊? –

回答

1

這將給得到<之間所有塊的內容-------->作爲分隔符

$pattern = '/<-{9}>([\S\s]*?)<-{9}>/'; 

$subject = " 
<---------> 
Content to get 
content to get 
content to get 
<---------> 
Some extra stuff 
<---------> 
Content to get 
content to get 
content to get 
<--------->"; 

$matches = array(); 
preg_match_all($pattern, $subject, $matches); 



$allBlocks = $matches[1]; 


foreach($allBlocks as $block) 
{ 
    var_dump(explode("\n", $block)); 

} 

但是,應該嘗試更加有條理地定義分隔符。

由於您的內容的開頭與內容的結尾相同。 <--------->縮放你的代碼時,你可能會在以後的麻煩,或者如果內容還包含<--------->

嘗試實現像</-------->一些XML標籤或自定義表單。

## BOU ##的東西\ñ東西## EOU ##

AS BOU/EOU是有用的東西

要提取基於<---------->這個定界符內容
+0

看起來像它的作品謝謝! –

-1
<?php 
// $sections will be an array with elements that contains rows between <----> 
$sections = explode(PHP_EOL.'<--------->'.PHP_EOL, file_get_contents("foo.txt")); 
?> 

現在你可以在iterrate段和再次PHP_EOL爆炸,那麼你會得到數組,其中每個元素是文件的一行。

如果您需要,可以將PHP_EOL更改爲「\ r」或「\ n」。

編輯:

<?php 

    $sections = explode(PHP_EOL.'<--------->'.PHP_EOL, file_get_contents("foo.txt")); 

    // each section contains file content between <---------> and next <---------> (additionaly start of file when it does not starts with <---------> 
    foreach ($sections as $section){ 

     $rows = explode(PHP_EOL, $section); 

     foreach($rows as $row){ 

      // display section row 
      echo $row.'<br />'; 

     } 

    } 

?> 
+0

你的意思是我應該用你的解決方案替換foreach? –

+0

@Maytyn你的代碼仍然會給你'內容無用'部分,因爲'explode()'將在分隔符上中斷,而不是在分隔符之間提取內容。 –

+0

file_get_contents(「foo.txt」)以字符串形式返回文件內容。每行由新行分隔,新行默認爲PHP_EOL。通過以新行+ <-----> +新行的陣列進行爆炸,您將收到陣列,其中每個元素包含<----><---->之間的行。現在你可以通過數組元素來獲得單獨的行。 – Maytyn

0

您可以使用正則表達式。

<?php 
    $g = file_get_contents("foo.txt"); 
    preg_match('#\<---------\>\r\n(.*?)\r\n\<---------\>#s',$g,$matches); 
    print_r($matches[1]); 
?> 

會給輸出:

Content to get 
content to get 
content to get 
+0

感謝您的回答!它看起來不適合我:/ –

+0

@ N.Roal你可以顯示你的代碼嗎? –