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.
Related
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
}
}
I have this search script:
$search = $_GET["search"];
$logfile = $_GET['logfile'];
$file = fopen($logfile, "r");
?>
<head>
<title>Searching: <?php echo $search ?></title>
</head>
<?php
while( ($line = fgets($file) )!= false) {
if(stristr($line,$search)) {
// case insensitive
echo "<font face='Arial'> $line </font><hr><p>";
}
}
I want to filter out a specific string when searching for something in the txt file.
For example, the text file consists of this:
http://test.com/?id=2022458&pid=41&user=Ser_Manji
Ser_manji said "hello"
Ser_manju left the game
When you search for instance for "Ser_manji", I want to filter out this string:
http://test.com/?id=2022458&pid=41&user=Ser_Manji
But still display these two lines:
Ser_manji said "hello"
Ser_manju left the game
I hope this is possible, I myself tryied altering it so it wouldn't accept anything to do with lines that contained "test.com", but that didn't work.
This should work for you:
Just get your file into an array with file(). And use strpos() to check if the search needle is in the line and if not display the line.
<?php
$search = $_GET["search"];
$logfile = $_GET['logfile'];
$lines = file($logfile, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
?>
<head>
<title>Searching: <?php echo $search ?></title>
</head>
<?php
foreach($lines as $line) {
if(strpos($line, $search) === FALSE) {
echo "<font face='Arial'>$line</font><hr><p>";
}
}
?>
You just need to modify your if condition like so:
if (stristr($line, $search) && strpos($line,'test.com') === false)
I suppose you need to filter out logs according to a specific username. This seems more complex than finding the right php function.
So you got your search q: $search = $_GET['search'] which is a username.
You got your logs file: $file = fopen($logfile, 'r').
Please note: You use GET parameters to get the filename but your example link http://test.com/?id=2022458&pid=41&user=Ser_Manji doesn't contain any &logfile=logs.txt. I suppose you know what you're doing.
Now if your logs structure is {username} {action} then we know that a "space" splits the username from his action. We can use explode: $clues = explode(' ', $line); and now $username = $clues[0] and $action = clues[1].
So if ($username == $search) echo $action
Keep it simple and clean.
$search = $_GET["search"];
$logfile = $_GET['logfile'];
$file = fopen($logfile, "r");
while ($line = fgets($logfile)) {
$clues = explode(' ', $line);
$username = $clues[0];
$action = $clues[1];
if ($username == $search) {
echo $action;
}
}
You should test this by: http://test.com?search=user_1234&logfile=logs.txt if you are looking for user_1234 inside logs.txt file and so on..
If you want to match text (case insensitive) only at the beginning of the line, you could consider using a case insensitive and anchored regular expression, for filtering on a textfile ideally with the preg_grep function on array (e.g. via file) or with a FilterIterator on SplFileObject.
// regular expression pattern to match string at the
// beginning of the line (^) case insensitive (i).
$pattern = sprintf('~^%s~i', preg_quote($search_term, '~'));
For the array variant:
$result = preg_grep($pattern, file($logfile));
foreach ($result as $line) {
... // $line is each grep'ed (found) line
}
With the iterators it's slightly different:
$file = new SplFileObject($logfile);
$filter = new RegexIterator($file, $pattern);
foreach ($filter as $line) {
... // $line is each filtered (found) line
}
The iterators give you a more object oriented approach, the array feels perhaps more straight forward. Both variants operate with the PCRE regular expressions in PHP which is the standard regular expression dialect in PHP.
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.
I am trying to load in all of the images within a folder using php and then build out a table and pull text from a json file and put it next to each image. The goal is to have json that looks like this.
{
"Car1": {
"year":"2012"
},
"Car2": {
"year":"2011"
},
"Car3": {
"year":"2009",
"milage":"10,204"
}
}
The Car1, Car2 names will ultimately match the names of the actual images in the folder as well. So i want to grab the image and the correct section in the json file and build out a table listing them all out. So far i have the below php, but am not really sure how to put it all together, as you can see below, its just separate right now. Any suggestions on how to combine the php below to achieve the result i described?
6/1 Edit (New Code using answer below). This is on a page in the spot where i want all of this outputted and the &letter variable is passed from a form on another page. But when that form submits and this page fires off, nothing happens. Am i doing something incorrect?
$letter = $_POST['letter'];
//Call the path of the cars for the chosen letter
$path = "/images/PartsCars/".$letter."/";
$temp_files = scandir($path);
//Call the path for the json file in the chosen letter subfolder
$data = json_decode($string, true);
//Sort the pictures in this folder alphabetically
natsort($temp_files);
echo '<table cellspacing="5" cellpadding="5">';
//Loop through all pictures and json elements to build out the page
foreach($temp_files as $file)
{
if($file != "." && $file != ".." && $file != "Thumbs.db" && $file != basename(__FILE__))
{
echo '<tr>';
echo '<td><img src="'.$url.$file.'" alt="'.$file.'" style="width:300px;height:200px;"/></td>';
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
echo '<td>'.print_r($data['$file_name']).'</td>';
echo '</tr>';
}
}
echo '</table>';
I am using php json_decode for ease of use and using print_r to demo, you could use a foreach loop to print it out properly
$path = "./images/PartsCars/A/";
$temp_files = scandir($path);
$string = file_get_contents("/images/PartsCars/A/sample.json");
data = json_decode($string, true);
natsort($temp_files);
echo "<table>";
foreach($temp_files as $file)
{
if($file != "." && $file != ".." && $file != "Thumbs.db" && $file != basename(__FILE__))
{
echo '<tr>';
echo '<td><img src="'.$url.$file.'" alt="" /></td>';
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
echo '<td>'.print_r(data['$file_name']).'</td>';
echo '</tr>'
}
}
echo '</table>';
I need to find word count for all of the files within a folder.
Here is the code I've come up with so far:
$f="../mts/sites/default/files/test.doc";
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
This will count the words within a single file, how would I go about counting the words for all files within a given folder?
how about
$array = array( 'file1.txt', 'file2.txt', 'file3.txt' );
$result = array();
foreach($array as $f ){
$result[$f] = str_word_count(file_get_contents($f));
}
and using the dir
if ($handle = opendir('/path/to/files')) {
$result = array();
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..')
continue;
$result[$file] = str_word_count(file_get_contents('/path/to/files/' . $file));
echo "This file {$file} have {$result[$file]} words";
}
closedir($handle);
}
Lavanya, you can consult the manual of readdir, file_get_contents.
Assuming the doc files are plaintext and don't contain additional markup, you can use the following script to count all of the words in all of the files:
<?php
$dirname = '/path/to/file/';
$files = glob($dirname.'*');
$total = 0;
foreach($files as $path) {
$count = str_word_count(file_get_contents($path));
print "\n$path has $count words\n";
$total += $count;
}
print "Total words: $total\n\n";
?>
If you are using *nux than you can use system('cat /tmp/* | wc -w')
You can use $words = str_word_count(file_get_contents($filepath)) to get the word count of a text file, however this won't work for word docs. You'll need to find a library or external program that can read the .doc file format.