Reputation: 7194
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 advance.riad
Upvotes: 0
Views: 96
Reputation: 28765
$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);
Upvotes: 1
Reputation: 9713
$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--
Upvotes: 0
Reputation: 8344
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--
Upvotes: 3