PHP- trim() function not working - php

I have problem when used function trim() with this code
$handle = #fopen("55.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$d = explode(" ", $buffer);
foreach($d as $val) {
echo '<br>'.trim($val,'.'); //why not work
}
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
The trim() doesn't trim '.'.

Additional to the lines themselves, the fgets() function returns the line breaks from the file, which are after the dots in the string, thus preventing the dots from being trimmed, because they are not actually the last character.
Try to trim the dots and possible line breaks at the same time:
echo '<br>'.trim($val, ".\r\n");

do
substr(trim($val),1,stlen(trim($val)));
instead of
trim($val,'.');
if you want to remove the leading and trailing '.'

Related

Reduce looping execution time

i got 35 second to execution this code. how to reduce the execution time? what should i change in this source code.
$file_handle = fopen("WMLG2_2017_07_11.log", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
if (strpos($line, 'root#CLA-0 [WMLG2] >') !== false) {
$namafileA = explode('> ', $line);
$namafile = str_replace(' ', '_', $namafileA[1]);
$filenameExtension = $namafile.".txt";
$file = preg_replace('/[^A-Za-z0-9\-_.]/', '', $filenameExtension); // hapus special character kecuali "." dan "_"
} else {
$newfile = fopen("show_command_file_Tes2/$file", "a");
fwrite($newfile, $line);
}
}
fclose($file_handle);
I found some mistakes you did with the original code that could impact your performance, but I am not sure how much.
If I understand correctly, you are opening a log file and sorting the messages out to separate files.
You have not pasted an example from the log file, but I assume you have duplicate file targets, not every line of the log file has individual file targets.
Your code opens, but never closes the handles and it stays open during the script run. The file handles are not closing on outer-scope by garbage collector, you have to do it manually to release the resources.
Based on that you should store the file pointers (or at least close them) and re-use that handle what is already open. You are opening at least X line of handle during the execution and not closing it / reusing it where X is the line count in the file.
Other thing I noticed, your lines may be long ones, an that is a rare case where php's strpos() function could be slower than a regex matching the correct position of the string. Without the log file, I can't say for sure because preg_match() is pretty expensive function on simple / short strings (strpos() is way faster.)
If its a log file, most likely starts with that "root#CLA"... string, you should try to match that if you can specify the string position with ^ (begining of the string) or $ (end of string).
<?php
$file_handle = fopen("WMLG2_2017_07_11.log", "r");
//you 'll store your handles here
$targetHandles = [];
while (!feof($file_handle))
{
$line = fgets($file_handle);
if (strpos($line, 'root#CLA-0 [WMLG2] >') !== false)
{
$namafileA = explode('> ', $line);
$namafile = str_replace(' ', '_', $namafileA[1]);
$filenameExtension = $namafile . ".txt";
$file = preg_replace('/[^A-Za-z0-9\-_.]/', '', $filenameExtension); // hapus special character kecuali "." dan "_"
}
else
{
//no $file defined, most likely nothing to write yet
if (empty($file))
{
continue;
}
//if its not open, we'll make them open
if (empty($targetHandles[$file]))
{
$targetHandles[$file] = fopen("show_command_file_Tes2/$file", "a");
}
//writing the line to target
fwrite($targetHandles[$file], $line);
}
}
//you should close your handles every time
foreach ($targetHandles as $handle)
{
fclose($handle);
}
fclose($file_handle);

Don't echo things with certain characters

I have a php program that looks at a log file and prints it to a page (code below). I don't want the user of said website to be able to look at any line containing a /. I know I could use trim to delete certain characters, but is there a way to delete the entire line? For example, I want to keep something like "Hello" and delete something like /xx.xx.xx.xx connected. All the lines I wish to delete have the same common key, /. Peoples names in said log file have <>s around them, so I must use htmlspecialcharacters
$file = file_get_contents('/path/to/log', true);
$file = htmlspecialchars($file);
echo nl2br($file);
Thanks for your help!
EDIT:
Thanks for all of the answers, currently tinkering with them!
EDIT2:
final code:
<?php
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
$line = htmlspecialchars($line . "\n");
echo nl2br($line);
}
}
?>
Do you mean, like this?
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
// If the line doesn't contain a "/", echo it
echo $line . PHP_EOL;
}
}
For anyone wondering, PHP_EOL is the PHP constant for "end of line" and promotes consistency between different systems (Windows, UNIX, etc.).
If you are iterating through the file line by line you can check with preg_match if the line contains /character and skip the echo if it does. If not, first split them at new line and iterate over that array.
If you don't want to split the file you can probably use preg_replace with a regexp such as (^|\n).*/.*(\n|$) and replace with empty string.
Use the str_replace function -
http://php.net/manual/en/function.str-replace.php. Alternate solution (before escaping the special characters) -
/* pattern /\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/ = /xx.xx.xx.xx connected */
/* pattern will be replaced with "newtext" */
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines as $line)
$correctline = preg_replace( '/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/', 'newtext', $line );
echo $correctline;
}
<?php
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines AS $num => $line)
{
if ( strpos($line, "/") === false ) // Line doesn't contain "/"
{
echo htmlspecialchars($line) . "\n";
}
}
?>

php for loop to remove common words

I have a text file that maintains a list of words.
What I am trying to do is pass a string(sentence) to this function and remove the word from the string if it exists in the text file.
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words($string) {
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
$words = explode(" ",$string);
print_r($words);
for($i=0; $i <= count($words); $i+=1) {
for($j=0; $j <= count($common); $j+=1) {
if($words[$i] == $common[$j]){
unset($words[$i]);
}
}
}
}
?>
It doesn't seem to work however. The common words from the string are not being removed. instead I am getting the same string with the one I started.
I think I am doing the loop wrong. What is the correct approach and what am I doing wrong?
on the line
if($words[$i] == $common[$j]){
change it to
if(in_array($words[$i],$common)){
and remove the second for loop.
Try using str_replace():
foreach($common as $cword){
str_replace($cwrod, '', $string); //replace word with empty string
}
Or in full:
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words(&$string) { //changes the actual string passed with &
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
foreach($common as $cword){
str_replace($cword, '', $string); //replace word with empty string
}
}
?>

code was working, but suddenly stopped working

This code opens a text file, then checks to see if each word in the text file
Exists in a another large 2MB dictionary file.
If it does exist, it stores the line from the dictionary file into a variable.
The code was working, but then began to generate Server 500 errors, and now
It only lists about 7 matches and then loads nothing forever.
It used to list the 1000's of matches and then stop.
$file_handle = fopen("POSdump.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$words= explode(" ", $line );
foreach ($words as $word) {
$word = preg_replace('#[^\w+>\s\':-]#', ' ', $word);
$subwords= explode(" ", $word );
$rawword = $subwords[0];
$poscode = $subwords[1];
$rawword = strtoupper($rawword);
$handle = fopen("dictionary.txt","r"); //
if ($handle) {
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
if (preg_match('#\b'.$rawword.'\b#',$buffer)) {
echo $rawword;
echo "</br>";
}
}
}
}
}
?>
Try closing the file when you are done.
This seems to be a memory_limit error. use ini_set('memory_limit', -1) before starting the process.

Some characters in CSV file are not read during PHP fgetcsv()

I am reading a CSV file with php. Many of the rows have a "check mark" which is really the square root symbol: √ and the php code is just skipping over this character every time it is encountered.
Here is my code (printing to the browser window in "CSV style" format so I can check that the lines break at the right place:
$file = fopen($uploadfile, 'r');
while (($line = fgetcsv($file)) !== FALSE) {
foreach ($line as $key => $value) {
if ($value) {
echo $value.",";
}
}
echo "<br />";
}
fclose($file);
As an interim solution, I am just finding and replacing the checkmarks with 1's manually, in Excel. Obviously I'd like a more efficient solution :) Thanks for the help!
fgetcsv() only works on standard ASCII characters; so it's probably "correct" in skipping your square root symbols. However, rather than replacing the checkmarks manually, you could read the file into a string, do a str_replace() on those characters, and then parse it using fgetcsv(). You can turn a string into a file pointer (for fgetcsv) thusly:
$fp = fopen('php://memory', 'rw');
fwrite($fp, (string)$string);
rewind($fp);
while (($line = fgetcsv($fp)) !== FALSE)
...
I had a similar problem with accented first characters of strings. I eventually gave up on fgetscv and did the following, using fgets() and explode() instead (I'm guessing your csv is comma separated):
$file = fopen($uploadfile, 'r');
while (($the_line = fgets($file)) !== FALSE) // <-- fgets
{
$line = explode(',', $the_line); // <-- explode
foreach ($line as $key => $value)
{
if ($value)
{
echo $value.",";
}
}
echo "<br />";
}
fclose($file);
You should setlocale ar written in documentation
Note:
Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.
before fgetcsv add setlocale(LC_ALL, 'en_US.UTF-8'). In my case it was 'lt_LT.UTF-8'.
This behaviour is reported as a php bug

Categories