0

I have inputted a word from a user and i want to find that word in a text file.
My text file is like this.
--------------
name1:value1
name2:value2
name3:value3
...
...
--------------
So if my user inputs name1 so i want corresponding value1..
How can i do these? Can anyone help me..??

3
Contributors
9
Replies
37
Views
7 Years
Discussion Span
Last Post by trickist17
0
<?php
function find_value($input) {
// $input is the word being supplied by the user
$handle = @fopen("/users/edwin/list.txt", "r");
if ($handle) {
  while (!feof($handle)) {
    $entry_array = explode(":",fgets($handle));
    if ($entry_array[0] == $input) {
      return $entry_array[1];
      }
    }
  fclose($handle);
  }
return NULL;
}
?>

Edited by edwinhermann: n/a

0

Thanks.. I got the idea.....!!!!!!! Thank you..

0

Thank you so much for this, great idea!

Now I am totally new to PHP and I want to overwrite the value for a name with a variable $newvalue.
Somebody has an idea?
Probably very easy, but it's just too high for me at the moment.

Thank you!

1

This is a new question and you should really have started a new thread. But never mind, we're here now :)

Here's some code:

<?php
$text = "It happened when <name> turned his computer on.";
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$text);
echo $new_text; // It happened when Fred turned his computer on.
?>
0

Ok, thank you, but I already had that :)!

My problem starts when $text is an external file.

Heres My Code:

function getdata()	{
	$handle = fopen("titel.txt", "r+");
	while ( ($line = fgets($handle)) !== false) {
		echo "$line";};
	fclose($handle);	
	return NULL;
}
$content = getdata();
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$content);
echo $new_text;
1

Then why not simplify like this:

function getdata()	{
return file_get_contents("titel.txt");
}
$content = getdata();
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$content);
echo $new_text;

Or even better do away with the function, so like this:

$content = file_get_contents("titel.txt");
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$content);
echo $new_text;
Votes + Comments
welcome back
0

Am I just too stupid or why doesn't it replace <name> with Fred, although it echoes right.

By the way, thank you for the file_get_contents() function!

0

Do you actually have the characters <name> in your file? Otherwise you'll need to specify whatever it is that is in the file that you want replaced.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.