开发者

Take a particular string from a file using php

Dear All, i have a txt file like:

--start--
  jeff
--end--
--start--
  sophya
--end--

Now i need to collect the names like jeff and sophya into an array.How i do it?I use below code but its not give me proper output.

$data = file_get_contents('http://localhost/sample.txt');
$start_position = strstr($data,'--start--');
$end_position    = strpos($data,'--end--') ;
$value=substr($start_position,$end_position);
print_r($value);
exit();

My out put is : --end-- --start-- sophya --end--

is their any kind heart who help me to take two name into an array? thanks in开发者_StackOverflow社区 advance.riad


There are a few approaches you can use here... I would personally use a regular expression to match what you need. preg_match_all().

$contents = file_get_contents('http://localhost/sample.txt');

preg_match_all('/--start--(.*?)--end--/ms', $contents, $matches);

foreach($matches[1] as $name) {
    var_dump($name);
}

Note: This includes the end of line characters on each side. To exclude them from the names, and and whitespace use the pattern '/--start--\n\s*(.*?)\s*\n--end--/ms'

I should mention, the advantage of this is it will automatically ignore things that are not in the correct format.

e.g. In the following file, asd will be ignored.

--start--
  jeff
--end--
asd
--start--
  sophya
--end--


$data = file_get_contents('http://localhost/sample.txt');
$data = str_replace('--end--', ' ', $data);  // remove existence of --end--
$data = explode('--start--', $data);  // resulted array
unset($data[0]);
echo implode(' ', $data);


$data = '--start--
  jeff
--end--
--start--
  sophya
--end--';

preg_match_all('/--start--\n(.*)\n--end--/iu', $data, $matches);
var_dump($matches);

This asumes you allways have a new line after --start-- and before --end--

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜