Function explode simple text file - php

I have a simple text file (see below).
abc|1356243309
zzz|1356239986
yyy|1356242423
I want to simply extract all names before |. So the output should look like:
abc
zzz
yyy
Below is the string I've attempted to use. I've also tried file('visitornames.txt') etc. I'm not sure what im doing wrong :(. Tried a lot of things.
$string = file_get_contents('visitornames.txt');
$names = explode('|', $string);
foreach($names as $key) {
echo $key . '"<br/>';
}
No errors, but its simply not doing it correctly.

I would use file-function instead of file_get_contents. It returns file as array where every line is own item. Then you can foreach file content array. Variable you are looking for is first part of the line and that's why you can just echo $names[0].
$file = file('visitornames.txt');
foreach ($file AS $line) {
$names = explode('|', $line);
echo $names[0] . '<br/>';
}

You can extract all lines of a file with the file function, then take each first part of the explode and assign it to the result:
$names = array();
foreach (file('visitornames.txt') as $line)
{
list($names[]) = explode('|', $line, 2);
}
Alternatively there is SplFileObject that is similar but you can more easily extend from it:
class Names extends SplFileObject
{
public function current() {
list($name) = explode('|', parent::current(), 2);
return $name;
}
}
$names = new Names('visitornames.txt');
foreach ($names as $name)
{
echo $name, "<br />\n";
}

Related

PHP foreach overwrite value with array

I'm making a simple PHP Template system but I'm getting an error I cannot solve, the thing is the layout loads excellent but many times, can't figure how to solve, here my code
Class Template {
private $var = array();
public function assign($key, $value) {
$this->vars[$key] = $value;
}
public function render($template_name) {
$path = $template_name.'.tpl';
if (file_exists($path)) {
$content = file_get_contents($path);
foreach($this->vars as $display) {
$newcontent = str_replace(array_keys($this->vars, $display), $display, $content);
echo $newcontent;
}
} else {
exit('<h1>Load error</h1>');
}
}
}
And the output is
Title is : Welcome to my template system
Credits to [credits]
Title is : [title]
Credits to Credits to Alvaritos
As you can see this is wrong, but don't know how to solve it.
You're better off with strtr:
$content = file_get_contents($path);
$new = strtr($content, $this->vars);
print $new;
str_replace() does the replaces in the order the keys are defined. If you have variables like array('a' => 1, 'aa' => 2) and a string like aa, you will get 11 instead of 2. strtr() will order the keys by length before replacing (highest first), so that won't happen.
Use this:
foreach($this->vars as $key => $value)
$content = str_replace($key,$value,$content);
echo $content;

remove all but last comma

i have the following code:
while (list($key, $value) = each($arr)) {
$implode_keys_values = #"$key=$value,";
echo"$implode_keys_values";
}
which ends up echoing out xxxx=xxxx,xxxx=xxxx,xxxx=xxxx,xxxx=xxxx,
depending on how many keys/values there are.
how do I take this dynamically changing string and remove the very last comma on it?
keep in mind:
$implode_keys_values = substr($implode_keys_values,0,-1);
will not work, it will take out all the commas.
rtrim($implode_keys_values, ",") would cut trailing commas.
You can learn more about rtrim here at the PHP docs
$implode_keys_values = "";
while (list($key, $value) = each($arr)) {
$implode_keys_values .= #"$key=$value,";
}
echo rtrim($implode_keys_values, ",");
PHP has a function built in for that if the data in the array is not too complex (works for the xxxxxx values you have, can break with others):
echo http_build_query($arr, '', ',');
See http_build_query().
Another alternative is using iterators and checking if the current iteration is the last one. The CachingIterator::hasNext() method is helpful for that:
$it = new CachingIterator(new ArrayIterator($arr));
foreach($it as $key => $value) {
echo $key, '=', $value, $it->hasNext() ? ',' : '';
}
This variant does work with any data.
In your case, this would be a better way to implement implode():
$data = array();
while (list($key, $value) = each($arr)) {
$data[] = "$key=$value";
}
echo implode(",",$data);

read file matching lines using array using php

I want to be able to read through a plain text file and match a number of lines without the need to iterate over the text file multiple times. I am passing in an array with a list of strings I would like to match, which ideally, I would like to put into an array.
I can achieve the desired result using the code below, but it necessitates the reading of the text file multiple times.
function readFile($line){
$contents = file("test.txt");
if(preg_match("/$line*/i", $val)){
return($val);
}
}
Ideally, I would like to do the following:
// pass an array to the funciton which will parse the file once and match on the elements defined.
$v = readFile(array("test_1", "test_2", "test_2", "test_3"));
// return an array with the matched elements from the search.
print_r($v);
Any help would be much appreciated.
Thanks all!
$val = array();
foreach ($contents as $file) {
foreach ($line as $l) {
if (stristr($file, $l)) {
$val[] = $file;
break; // Don't need to check the other $line values
}
}
}
$val = array();
foreach ($contents as $file) {
foreach ($line as $l) {
if (stristr($file, $l) {
$val[] = $file;
}
}
}
Even if you want to stick with preg_match, the "*" is unnecessary.

How to put those content into the variable one by one and then output it?

Supposed a text file named name.txt. there are some contents as the following in it:
Michal Guiles,Tanika Mcall,Jerry Sanipasi,Fallon Mcgillivray,Kurtis Bouras,Maria Teschner,Jerry Barbot,Earnestine
how to put all the names into a variable named $name; then output them one by one by $comment->setname("$name");
Read the file :
$file_handle = fopen("myfile.text", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
}
fclose($file_handle);
Split the parts :
$parts = explode(",",$line);
Print them one by one :
foreach ($parts as $part)
{
echo "$part<br/>";
}
You're asking about multiple things at once. Just do one thing after the other:
Read the file: (see file_get_contents)
$text = file_get_contents('name.txt');
Retrieve the names: (see explode)
$names = explode(',', $text);
Iterate over the names: (see foreach)
foreach ($names as $name)
{
$comment->setname($name);
}

Reading text file and comparing line with the exact same line returns false

My current code:
$file = fopen("countries.txt","r");
$array = array();
while(!feof($file)) {
$array[] = fgets($file);
}
fclose($file);
Here is my foreach loop:
$str = "test";
foreach ($array as $key => $val) {
if ($val == $str) {
echo $val;
} else {
echo "not found";
}
}
I am wondering why it is only printing $val if it is the last value of the array.
For example, it works if the txt file looks like this
test1
test2
test3
test
but doesn't work if it looks like this
test1
test2
test
test3
The problem is, that you have a new line character at the end of each line, so:
test\n !== test
//^^ See here
That's why it doesn't work as you expect it to.
How to solve it now? Can I introduce to you the function: file(). You can read a file into an array and set the flag to ignore these new lines at the end of each line.
So putting all this information together you will get this code:
$array = file("countries.txt", FILE_IGNORE_NEW_LINES);
$str = "test";
foreach ($array as $key => $val) {
if ($val == $str) {
echo $val;
} else {
echo "not found";
}
}
When you compare strings - you should always use '==='.

Categories