I have a text file "output.txt" which is an output of a shell command. I want to highlight certain words taken as $_GET['word'] in that file and then allow to download using href.
I have seen multiple questions but none of them seems to be working in this case.
Highlight multiple keywords from a given string
highlight the word in the string, if it contains the keyword
Code:
$cmd = shell_exec("/usr/local/bin/clustalw2 -infile=input.txt -tree -type=protein -case=upper &");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = $_GET['word'];
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, $content);
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";
It is not giving any error neither highlighting the text.
I suspect the trouble is with opening the initial file. The following did work for me.
I created /home/input.txt:
this is a test
that may
or may not work.
Then ran:
$cmd = shell_exec(" cp /home/input.txt output.txt");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = "may";
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, implode("\n", $content));
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";
And the output.txt is now:
this is a test
that <span style="color:red">may</span>
or <span style="color:red">may</span> not work.
Related
I got some files to change by clicking a button. To go for it, i have the old string to replace, saved in database, and also the new one.
On the click button, it executes a function that is gonna find the old string in the PHP file, then gonna replace it by the new one. (Final goal is to automate the PHP edits in a web software after an update).
My problem is that it perfectly works on short strings (without newline), but as soon as there is a newline into the file, nothing happens.
This is my actual code :
$path = '/mypath/' . $item['path'];
$old_code = $item['old_code'];
$new_code = $item['new_code'];
}
$pos = strpos(file_get_contents($path), $old_code);
$file = file_get_contents($path);
$str = str_replace($old_code, $new_code, $file);
file_put_contents($path, $str);
$pos is "true" if my $old_code doesn't have any newline.
I tried to use preg_match to remove \n, but the problem is that when i'll have to push my edits on the file with file_put_contents, every newline will also disapear.
Example of non-working str_replace :
echo "ok"; echo 'hey there is some spaces before'
echo 'this is a sentence';
$menu = ['test1', 'test200'];
print_r($menu);
$url = "/link/to/test";
$div = "echo \"<div class='central_container' align='center'>\";";
Do you have any idea for resolving this ?
Thanks
if I`m not wrong str_replace() work only with single lines . Its have 2 options.
Option line replace str_replace() with preg_replace() or just use https://regex101.com/ there also have code generator after you finish you Regex
I have a TEXT file bla.txt
REGION_NAME = 'bla_2'
hello
hi
goodbye
my script##
<?php
$file = 'bla.txt';
$file_contents = file_get_contents($file);
$fh = fopen($file, "w");
$file_contents = preg_replace("/(REGION_NAME =) ('')/", "$1 'us-east-A'", "REGION_NAME = ''");
fwrite($fh, $file_contents);
fclose($fh);
?>
When I run it, It adds the correct text but then overwrites the bla.txt file
so and I loose the other words.
NOTE:### If I use str_replace works fine but once bla_2 changes then we can't use the script again...
Any Idea...?
$file_contents = str_replace('bla_2','bar',$file_contents);
If you read the code you are overwriting the initial value of $file_contents, not replacing against the data in $file_contents. What you need to do is: $file_contents = preg_replace("/(REGION_NAME =) ('')/", "$1 'us-east-A'", $file_contents);. And as a disclaimer I didn't actually run your code but you weren't passing in the correct subject for the function from what I see.
And I think what you want for regex is something along the lines of preg_replace("REGION_NAME = '(.*)'", 'us-east-A', $file_contents)
I am trying to read a .tsv file using PHP. I am using the simplest method of file_get_contents() but it is skipping any text between <> tags.
Following is the format of my .tsv file
<id_svyx35_88c_avbfa5> <Kuldeep_Raval> rdf:type <wikicat_Delhi_Daredevils_cricketers>
Following is the code I am using
$filename = "access_s.tsv";
$content = file_get_contents($filename);
//Split file into lines
$lines = explode("\n", $content);
echo $content;
On reading it, the output is just
rdf:type
Please help in what can be the solution to read the line as it is?
Try to apply htmlspecialchars() to $content:
$filename = "access_s.tsv";
$content = htmlspecialchars(file_get_contents($filename));
//Split file into lines
$lines = explode("\n", $content);
echo $content;
Reference on php.net
The tags have always been there, the browser just does not show them. Just like with any valid HTML tag, you can see them when viewing the source code of the website.
I'm pulling my hair out trying to do a preg_replace in php and store the results in a csv file.
I want to replace \" in a string with \"" and the closest I can get to currently is \ "".
The problem is that fputcsv automatically adds a doublequote to an existing doublequote which is fine, APART FROM if the doublequote is already escaped
Here's some example code:
$code = 'document.body.innerHTML.toLowerCase().replace(/\s|\"/g, "");';
$pattern = '(\\\")';
$replacement = '\\\ "';
$content[] = preg_replace($pattern, $replacement, $code);
$filename = "test.csv";
$temp_filename = "tempfile";
$fp = fopen($tempfilename, 'w');
fputcsv($fp, $content);
fclose($fp);
In the resulting CSV file, the cell shows \ "" as demonstrated below:
"document.body.innerHTML.toLowerCase().replace(/\s|\ ""|/g, """");"
So this is nearly correct, but it needs to be \"" and not \ ""
Can anyone help me write the correct $replacement variable so that it will output \"" in the csv?
I've tried:
$replacement = '\\\""'; which produces \"""
$replacement = '\\\"'; which produces \"
So \"" is eluding me
Many many thanks if you can assist!
I want to find a specific text string in one or more text files in a directory, but I don't know how. I have Googled quite a long time now and I haven't found anything. Therefor I'm asking you guys how I can fix this?
Thanks in advance.
If it is a Unix host you're running on, you can make a system call to grep in the directory:
$search_pattern = "text to find";
$output = array();
$result = exec("/path/to/grep -l " . escapeshellarg($search_pattern) . " /path/to/directory/*", $output);
print_r($output);
// Prints a list of filenames containing the pattern
You can get what you need without the use of grep. Grep is a handy tool for when you are on the commandline but you can do what you need with just a bit of PHP code.
This little snippet for example, gives you results similar to grep:
$path_to_check = '';
$needle = 'match';
foreach(glob($path_to_check . '*.txt') as $filename)
{
foreach(file($filename) as $fli=>$fl)
{
if(strpos($fl, $needle)!==false)
{
echo $filename . ' on line ' . ($fli+1) . ': ' . $fl;
}
}
}
If you're on a linux box, you can grep instead of using PHP. For php specifically, you can iterate over the files in a directory, open each as a string, find the string, and save the file if the string exists.
Just specify a file name, get the contents of the file, and do regex matching against the file contents. See this and this for further details regarding my code sample below:
$fileName = '/path/to/file.txt';
$fileContents = file_get_contents($fileName);
$searchStr = 'I want to find this exact string in the file contents';
if ($fileContents) { // file was retrieved successfully
// do the regex matching
$matchCount = preg_match_all($searchStr, $fileContents, $matches);
if ($matchCount) { // there were matches
// $match[0] will contain the entire string that was matched
// $matches[1..n] will contain the match substrings
}
} else { // file retrieval had problems
}
Note: This will work irrespective of whether or not you're on a linux box.