PHP Replace string in text file using - php

I have a file with usernames and displaynames store in it like this:
testname=displayname<br>
testname2=displayname2<br>
etc=etc<br>
This list is done twice on the same file, same usernames and same displaynames. I need to replace them in both areas in the lists (needs to be replaced twice)
I am trying to create a form where uses can change their display name. I was trying to copy my code from a page where it looked up passwords for their accounts in a file, found it, and replaced it, however it doesn't seem to be working for this file.
The form for changing their names is simple, it has them enter in their member name (so I could use that to have it find their name in the list) and then uses what they input for a display name to change their display name in the file.
Form Page Code:
<center>Change Display Name:<p>
<form action="http://example.com/xxx/displaynamesave.php" class="form" method="post">
<input "membername" name="membername" /><p><input "displayname" name="displayname" /><p><input name="Submit" type="submit" /></form></p>/center>
and below is my php code for processing
<?
$fileurl = '/xxx/myfiles/sitename/xxx/memberfiletest';
$membername = $_POST['membername'];
$displayname = $_POST['displayname'];
$file = file($fileurl, FILE_IGNORE_NEW_LINES); // Get file as array of lines
foreach ($file AS $n=>$line)
if (substr($line, 0, 20) === '$membername') // Line starts with 'membername'
$file[$n] = '$membername = '.$displayname; // Replace displayname
file_put_contents($fileurl, implode("\n", $file)); // Put file back together
$success_page = 'http://example.com/thisplace/xxx/xxx/successredirector.html';
header('Location: '.$success_page);
?>
When I input the data and hit submit, it goes to my success page, however it doesn't make any changes in the proper file and I'm unsure how to tell what I'm missing.

First, your comparison shows the variable in single quotes ', which means PHP won't parse it and is in fact comparing everything to $membername, and not the value of the variable $membername. Change the comparison to:
foreach ($file as $n => $line) {
if (substr($line, 0, 20) === $membername) { // Line starts with 'membername'
$file[$n] = $membername . ' = ' . $displayname; // Replace displayname
}
}
Second, in the example of the contents of your file, the "username" portion are not all the same length ("testname", "etc"), but your comparison is checking against the first 20 characters of the line. If the format is indeed username=displayname, you would probably have better results splitting the line on the = (there are a couple ways to do this, of course), and comparing the first part. An example would be something like :
foreach ($file as $n => $line) {
$parts = explode('=', $line);
if ($parts[0] == $membername) {
$file[$n] = $membername . ' = ' . $displayname;
}
}

Use strpos
foreach ($file as $n => $line) {
if (strpos($line, $membername) === 0) { // Line starts with 'membername'
$file[$n] = $membername . ' = ' . $displayname; // Replace displayname
}
}

You're using variables inside a '. Try this:
foreach ($file as $n => $line) {
list($name, $dname) = explode('=', trim($line));
if ($name === $membername) { // Line starts with 'membername'
$file[$n] = $membername . ' = ' . $displayname; // Replace displayname
}
}

Related

Pass multiple php variables to index page

Update
is there anyway i can use the following code to replace $anagram within the $description using the following code because it will strip what-is-an-anagram-of-listen.php and the output would be listen?
$anagram = str_replace('what-is-an-anagram-of-', ' ', pathinfo($file, PATHINFO_FILENAME));
I have a php script which will list all the files of a certain folder.
It takes the page title and strips it of dashes and uses it as title then it takes the description of the page and echos it.
<?php
if ($handle = opendir('../anagram/')) {
$fileTab = array();
preg_match("/name=\"description\" content=\"(.*?)\"/i", file_get_contents("../anagram/".$file), $matches);
$description = $matches[1];
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != 'index.php' && $file != 'error_log') {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach($fileTab as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents("../anagram/".$file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/description = \"(.*?)\"/i", $content,$matches);
$description = $matches[1];
}
$buy .= '<div class="indexpage"><h6>'.$title.'</h6><p>'.$description.'</p><p><a class="button-blue-short" href="../anagram/'.$file.'">Read More »</a></p></div>';
}
}
?>
<?=$buy?>
The following code is an example of one of the pages in the folder ../anagram/ the index page reads the description and uses it to create the index page.
<?php
$anagram = "listen";
$pagetitle = "What is an Anagram of $anagram";
$keywords = "Anagram of $anagram";
$description = "What is an Anagram of $anagram, an anagram is creating a word or phrase by moving around the letters of a different word or phrase, using all the original letters of $anagram what other words can be made from the word $anagram.";
include("../include/head.php");
?>
My problem is on my index page I can’t get the php code to read $anagram from the $desription it just echos it as $anagram but it should say listen.
See: https://www.php.net/manual/en/language.types.string.php
Depending on your setup and PHP version, putting a variable in double quotes should produce the correct output, but you have several other options available:
<?php
$anagram = "listen";
$test1 = "some text ${anagram} more text\n";
$test2 = "some text {$anagram} more text\n";
$test3 = "some text ".$anagram." more text\n";
echo $test1;
echo $test2;
echo $test3;
?>
Should all work correctly.

PHP - Searching words in a .txt file

I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}

Get value from file - php

Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];

Write PHP to find a word in a text file using a loop

Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.
The JavaScript part is correct but I'm having trouble with PHP:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
If it's only 50 words then just make an array out of it and check if it's in the array.
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
You are not searching the "word" into your code, but maybe the code below will help you
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
here is something fancy, regular expression :)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.
here is a working example : http://ideone.com/LmgksA
You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
This matches any word token in a string.

PHP search text file line by line for two strings then output line

I am trying to search a text file for two values on a line. If both values are present I need to output the entire line. The values I am searching for may not be next to each other which is where I am getting stuck. I have the following code which works well but only for one search value:
<?php
$search = $_REQUEST["search"];
// Read from file
$lines = file('archive.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}
?>
Any assistance much appreciated. Many thanks in advance.
Assuming the values you're searching for are separated by a space, and they will both always be present, explode should do the trick:
$search = explode(' ', $_REQUEST["search"]); // change ' ' to ',' if you separate the search terms with a comma, etc.
// Read from file
$lines = file('archive.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search[0]) !== false && strpos($line, $search[1] !== false)) {
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}
}
I'll leave it up to you to add some validation to make sure there are always two elements in the $search array, etc.
I also corrected the HTML code. The script looks for two values, $search and $search2. It is using stristr(). For the case-sensitive version of stristr, refer to strstr(). The script will return all lines containing both $search and $search2.
<?php
$search = $_REQUEST["search"];
$search2 = $_REQUEST['search2'];
// Read from file
$lines = file('archive.txt');
echo"<html><head><title>SEARCH RESULTS FOR: $search</title></head><body>";
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(stristr($line,$search) && stristr($line,$search2)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
?>
</body></html>
Just search for your other value also and use && to check for both.
<?php
$search1 = $_REQUEST["search1"];
$search2 = $_REQUEST["search2"];
// Read from file
$lines = file('archive.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search1) !== false && strpos($line, $search2) !== false)
echo"<html><title>SEARCH RESULTS FOR: $search1 and $search2</title><font face='Arial'> $line <hr>";
}
?>
This worked for me. You may define what you like in searchthis aray and it will be displayed with whole line.
<?php
$searchthis = array('1','2','3');
$matches = array();
$handle = fopen("file_path", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
foreach ($searchthis as $param) {
if(strpos($buffer, $param) !== FALSE)
$matches[] = $buffer;
}}
fclose($handle);
}
foreach ($matches as $parts) {
echo $parts;
}
?>

Categories