I have a file, that contain:
file content NULNULNULNUL something else.
When I try get file content
$str = file_get_contents($fileName), in $str appear just file content.
How I can replace the NUL in file, without open file?
1.) To get the replaced content as a string. First get the file content just like you did.
$str = file_get_contents($fileName)
Then replace all occurances of NUL with a blank space like:
$new_content = str_replace('NUL'," ",$str);
OR
2.) To replace the content inside the file (to replace content and write it back to the file):
file_put_contents($fileName,str_replace('NUL',' ',file_get_contents($fileName)));
here we are using file_put_contents — which writes a string to a file. We pass the filename and the replaced-string as a parameter
I convert each character to assci code. This is work now:
$newStr='';
$str = file_get_contents($fileName);
$length = strlen($str);
for ($i=0; $i < $length; $i++)
{
$current = ord($str{$i});
if ($current != 0x0)
{
$newStr .= chr($current);
}
else
{
$newStr .= "";
}
}
$num = file_put_contents($fileName,$newStr);
Related
I just started to code in php, and I got a task to do.
I have to read non-ascii characters like the " character from a file, convert them to a string array, the convert into integers,and add numbers to them.
For example, if I have the '"' character, I should get 147, then if I add -31 to it, it should return the character 't'.
Here is a code i tried;
$file = fopen("word.txt", "r") or die("File missing");
$wholefile=fread($file, filesize("word.txt"));
fclose($file);
$words =explode(chr(0x0A), $wholefile);
$file = fopen("password.txt", "r") or die("File missing");
$wholefile=fread($file, filesize("password.txt"));
fclose($file);
$words =explode(chr(0x0A), $wholefile);
//An exmaple
$str = $words[0];
for($i = 0; $i< strlen($str); $i++)
{
$str[$i] = chr(ord($str[$i]) - 31);
}
echo "$str";
Can you help me to get ascii characters isntead of ��-s?
The content of the file (exmaple)
pS“`nf2†ddn^MZrrŠ
I'm loading a file by this script:
$hFile = fopen($sFile, "r");
$sContent = "";
while(!feof($hFile)) {
$sContent .= fread($hFile, 4096);
}
fclose($hFile);
It works as it should do, but i tried to load a file called test.txt
which contains the following string: <>863b?)(/&(§&/))!)!=WLKM! K!*ÜQWW!W3³³w2_:LPE
The variable $sContent now doesn't contain anything.
$html = mb_convert_encoding($html, "UTF-8");
Do this before writing to the file in the first place.
I'm running into an issue with finding specific text and replacing it with alternative text.
I'm testing my code below with .rtf and .txt files only. I'm also ensuring the files are writable, from within my server.
It's a hit and miss situation, and I'm curious if my code is wrong, or if this is just weirdness of opening and manipulating files.
<?php
$filelocation = '/tmp/demo.txt';
$firstname = 'John';
$lastname = 'Smith';
$output = file_get_contents($filelocation);
$output = str_replace('[[FIRSTNAME]]', $firstname, $output);
$output = str_replace('[[LASTNAME]]', $lastname, $output);
$output = str_replace('[[TODAY]]', date('F j, Y'), $output);
// rewrite file
file_put_contents($filelocation, $output);
?>
So, inside the demo.txt file I have about a full page of text with [[FIRSTNAME]], [[LASTNAME]], and [[TODAY]] scattered around.
It's hit and miss with the find/replace. So far, [[TODAY]] is always replaced correctly, while the names aren't.
Has anyone had this same issue?
(on a side note, I've checked error logs and so far no PHP warning/error is returned from opening the file, nor writing it)
Hard to say for sure without seeing the contents of demo.txt. My first guess is that it might be a problem with using brackets for your pointers. I would try changing to something not used by RTF like percent signs or an asterisk. ex: %%FIRSTNAME%%, **FIRSTNAME** (this is assuming of course that you have control of the contents of demo.txt.)
I have had this issue too. It seems like Microsoft Word inserts formatting codes in the tags. I have made a blog post about how to get around this on my technical blog.
http://tech.humlesite.eu/2017/01/13/using-regular-expression-to-merge-database-content-into-rich-text-format-template-documents/
The PHP example is shown here:
<?php
$file = file_get_contents('mergedoc.rtf');
// To temporary get rid of the escape characters...
$mergetext = str_replace("\\", "€€", $file);
// New seven part regex with default value detection
$regex2 = '/<<((?:€€[a-z0-9]*|\}|\{|\s)*)([a-z0-9.\-\+_æøåÆØÅA-Z]*)((?:€€[a-z0-9]*|\}|\{|\s)*)([a-z0-9.\-\+_æøåÆØÅA-Z]*)((?:€€[a-z0-9]*|\}|\{|\s)*)(?:\s*:(.*?)\s*)?((?:€€[a-z0-9]*|\}|\{|\s)*)>>/';
// Find all the matches in it....
preg_match_all($regex2,$mergetext, $out, PREG_SET_ORDER);
// Lets see the result
var_dump($out);
foreach ($out as $match) {
$whole_tag = $match[0]; // The part we actually replace.
$start = $match[1]; // The start formatting that has been injected in our tag, if any
$tag = $match[2]; // The tag word itself.
if (($match[4].$match[6]) != "") { //some sec-part tag or default value?
$end = $match[5]; // The end formatting that might be inserted.
if ($end == "") {
$end = $match[7]; // No end in 5, we try 7.
}
} else {
$end = $match[3]; // No second tag or default value, we find end in match-3
}
$secPartTag = $match[4]; // Do we have inserted some formatting inside the tag word too ?
if ($secPartTag != "") {
$tag .= $secPartTag; // Put it together with the tag word.
}
$default_value = $match[6];
// Simple selection of what we do with the tag.
switch ($tag) {
case 'COMPANY_NAME':
$txt = "MY MERGE COMPANY EXAMPLE LTD";
break;
case 'SOMEOTHERTAG':
$txt = "SOME OTHER TEXT XX";
break;
case 'THISHASDEFAULT':
$txt = "";
break;
default:
$txt = "NOTAG";
}
if ($txt == "") {
$txt = $default_value;
}
// Create RTF Line breaks in text, if any.
$txt = str_replace(chr(10), chr(10)."\\line", $txt);
// Do the replace in the file.
$mergetext = str_replace($whole_tag, $start.$txt.$end, $mergetext);
}
// Put back the escape characters.
$file = str_replace("€€", "\\", $mergetext);
// Save to file. Extention .doc makes it open in Word by default.
file_put_contents("ResultDoc.doc", $file);
?>
I want to covert all the characters in a file to ASCII code in php? I know of ord function but whether there is any function that will do for the entire file?
iconv may do the work
http://php.net/manual/de/function.iconv.php
it convertes chars of a specified charset in a string to another one. look at the //TRANSLIT and //IGNORE specials for chars that cannot be converted 1:1.
to get the file in a string you can use file_get_contents and save it after iconv etc. is applied with file_put_contents.
$inputFile = fopen("input.txt", "rb");
$outputFile = fopen("output.txt", "w+");
while (!feof($inputFile)) {
$inputBlock = fread($inputFile, 8192);
$outputBlock = '';
$inputLength = strlen($inputBlock);
for ($i = 0; $i < $inputLength; ++$i) {
$outputBlock .= str_pad(dechex(ord($inputBlock{$i})),2,'0',STR_PAD_LEFT);
}
fwrite($outputFile,$outputBlock);
}
fclose($inputFile);
fclose($outputFile);
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
}
}
?>