Member Avatar for kirtan_thakkar

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..??

<?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;
}
?>
Member Avatar for kirtan_thakkar

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

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!

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.
?>

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;

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;
commented: welcome back +14

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!

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.

I actually used exactly your script, but put $text into an external file!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.