2016-05-17 66 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你可以显示你的代码吗? –