php remove a line after specific words with str_replace - php

there is text in file as example:
<div class="from">jack</span></div>
hey u
<div class="from">ron</span></div>
bye
i am trying to delete the new line tag after "" and replace "|"
the result i need is:
<div class="from">jack</span></div>|hey u
<div class="from">ron</span></div>|bye
i tried this but think i got it wrong because it do the job.
$string = file_get_contents($filename);
$string = str_replace('/(<\/span><\/div>\r\n)', '|', $string);
file_put_contents($filename, $string);
what is the correct way?
thanks

<?php
$string = '<div class="from"><span>jack</span></div>
hey u';
echo preg_replace('/\r\n/', '|', $string);

$file_handle = fopen($filename, "r");
$text = "";
while (!feof($file_handle)) {
$line = fgets($file_handle);
if (strpos($line,'<div>') !== false) {
$line = preg_replace('/\r\n/', '|', $line)
}
$text .= $line;
}
file_put_contents($filename, $text);
fclose($file_handle);
Hows that for reading the file line by line, if the line has a tag, it replaces \n\r, and then at the end writes all of the lines back into the file.

It depends on what line ending is used, there's three possible ones, \n, \r\n, and \r.
Try this:
$string = str_replace('/(<\/span><\/div>\n)', '|', $string);
Also the first slash in that string is suspect, so try this:
$string = str_replace('(<\/span><\/div>\r\n)', '(<\/span><\/div>|', $string);

Related

Preg_replace in foreach doesn't work properly

I have a problem with a PHP Code. This loop only executes the last regular expression in the file and when I change the sequence of expressions in the file and another expression becomes last, only this new last expression is executed.
foreach(file('general.txt') as $line) {
$text = preg_replace("/" . $line . "/", "", $text);
}
The file general.txt contains lines of regular expressions, everything tested. But in this loop, it doesn't work anymore.
Do you maybe know why this is like this? I have tried a lot, but didn't figure out why...
Thank you
Simon
you need to trim your lines as follows:
foreach(file('general.txt') as $line) {
$text = preg_replace("/" . trim($line) . "/", "", $text);
}
Instead of using the file() function, you can use fopen and stream_get_line that removes the newline sequence. To do that, you must know the newline sequence used in your pattern file. Exemple with a Windows newline sequence:
$fh = fopen('patterns.txt', 'r');
if ($fh) {
$nl = "\r\n";
while ( false !== $line = stream_get_line($fh, 2048, $nl) ) {
$str = preg_replace('/' . $line . '/', '', $str);
}
}
A significant advantage over trim: you can use patterns that start or end with whitespaces.

including leading whitespaces when using fgets in php

I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.
Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.
Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.
Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps
I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).

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";
}
}
?>

Reading text after a certain character in php

Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>

Text file into an array?

In php how can I read a text file and get each line into an array?
I found this code which does it, somewhat, but looks for a = sign and I need to look for a new line:
<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('=', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>
Well, you could just replace the '=' with a "\n" if the only difference is that you're looking for a newline.
However, a more direct way would be to use the file() function:
$lines = file("dictionary.txt");
That's all there is to it!
Use php's file function:
file — Reads entire file into an array
Example:
$lines = file('dictionary.txt');
echo $lines[0]; //echo the first line
So, use the character for a newline instead of the '='
'\n'
Rather than using '=', use '\n'.
Example (also strips '\r' characters, for files which use '\r\n' as their line delimiter):
<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$line_of_text = str_replace('\r', '', $line_of_text);
$parts = explode('\n', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>
Note: This code example won't work on files which use '\r' by itself to specify newlines.

Categories