how to replace a string inside files using php - php

I intend to create a simple codes using php that can replace strings inside the files much like replace function in the notepad and ms word but the difference is it will replace all strings match to the desired string to change in all files inside the folder any Idea how to do that?

You can use useful glob() php function.
Example
<?php
$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');
foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("Hello","World",$file_contents);
file_put_contents($path_to_file,$file_contents);
}
?>
If You have sub folders in your directory then you can get files with the below code
$path = realpath(__DIR__ . '/textfiles/'); // Path to your textfiles
$files_in_your_folder = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);

Related

How to read only the folders

I have this code that reads all the content of a folder and converts it to an array, but I want to only the code reads folders and no files.
For example in language file are these files and folders:
../
en_EN/
fr_FR/
happy.rar
And the code is:
$folder = '../language/';
$return = scandir($folder, 1);
$return = array_diff($return, array('.', '..','error_log','_notes'));
$return = str_replace(".php", "", $return);
I can make exceptions in the 3rd line, but I want to create an exception for all the files.
Is there a way to make that?
Thank you
You can use glob() to select only folders simply as per below with GLOB_ONLYDIR flag.
and use basename() to get only folder name.
$a = glob("../language/*", GLOB_ONLYDIR ); // $a has only folders
foreach($a as $file){
echo(basename($file));
}

Read and replace contents in .docx (Word) file

I need to replace content in some word documents based on User input. I am trying to read a template file (e.g. "template.docx"), and replace First name {fname}, Address {address} etc.
template.docx:
To,
The Office,
{officeaddress}
Sub: Authorization Letter
Sir / Madam,
I/We hereby authorize to {Ename} whose signature is attested here below, to submit application and collect Residential permit for {name}
Kindly allow him to support our International assignee
{name} {Ename}
Is there a way to do the same in Laravel 5.3?
I am trying to do with phpword, but I can only see code to write new word files - but not read and replace existing ones. Also, when I simply read and write, the formatting is messed up.
Code:
$file = public_path('template.docx');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);
$phpWord->save('b.docx');
b.docx
To,
The Office,
{officeaddress}
Sub:
Authorization Letter
Sir / Madam,
I/We hereby authorize
to
{Ename}
whose signature is attested here below, to submit a
pplication and collect Residential permit
for
{name}
Kindly allow him to support our International assignee
{name}
{
E
name}
This is the working version to #addweb-solution-pvt-ltd 's answer.
//This is the main document in Template.docx file.
$file = public_path('template.docx');
$phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);
$phpword->setValue('{name}','Santosh');
$phpword->setValue('{lastname}','Achari');
$phpword->setValue('{officeAddress}','Yahoo');
$phpword->saveAs('edited.docx');
However, not all of the {name} fields are changing. Not sure why.
Alternatively:
// Creating the new document...
$zip = new \PhpOffice\PhpWord\Shared\ZipArchive();
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$file = public_path('template.docx');
$temp_file = storage_path('/app/'.date('Ymdhis').'.docx');
copy($template,$temp_file);
if ($zip->open($temp_file) === TRUE) {
//Read contents into memory
$oldContents = $zip->getFromName($fileToModify);
echo $oldContents;
//Modify contents:
$newContents = str_replace('{officeaddqress}', 'Yahoo \n World', $oldContents);
$newContents = str_replace('{name}', 'Santosh Achari', $newContents);
//Delete the old...
$zip->deleteName($fileToModify);
//Write the new...
$zip->addFromString($fileToModify, $newContents);
//And write back to the filesystem.
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
Works well. Still trying to figure how to save it as a new file and force a download.
I have same task to edit .doc or .docx file in php, i have use this code for it.
Reference : http://www.onlinecode.org/update-docx-file-using-php/
$full_path = 'template.docx';
//Copy the Template file to the Result Directory
copy($template_file_name, $full_path);
// add calss Zip Archive
$zip_val = new ZipArchive;
//Docx file is nothing but a zip file. Open this Zip File
if($zip_val->open($full_path) == true)
{
// In the Open XML Wordprocessing format content is stored.
// In the document.xml file located in the word directory.
$key_file_name = 'word/document.xml';
$message = $zip_val->getFromName($key_file_name);
$timestamp = date('d-M-Y H:i:s');
// this data Replace the placeholders with actual values
$message = str_replace("{officeaddress}", "onlinecode org", $message);
$message = str_replace("{Ename}", "ingo#onlinecode.org", $message);
$message = str_replace("{name}", "www.onlinecode.org", $message);
//Replace the content with the new content created above.
$zip_val->addFromString($key_file_name, $message);
$zip_val->close();
}
To read and replace content from Doc file, you can use PHPWord package and download this package using composer command:
composer require phpoffice/phpword
As per version v0.12.1, you need to require the PHP Word Autoloader.php from src/PHPWord folder and register it
require_once 'src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
1) Open document
$template = new \PhpOffice\PhpWord\TemplateProcessor('YOURDOCPATH');
2) Replace string variables for single
$template->setValue('variableName', 'MyVariableValue');
3) Replace string variables for multi occurrence
- Clone your array placeholder to the count of your array
$template->cloneRow('arrayName', count($array));
- Replace variable value
for($number = 0; $number < count($array); $number++) {
$template->setValue('arrayName#'.($number+1), htmlspecialchars($array[$number], ENT_COMPAT, 'UTF-8'));
}
4) Save the changed document
$template->saveAs('PATHTOUPDATED.docx');
UPDATE
You can pass limit as third parameter into $template->setValue($search, $replace, $limit) to specifies how many matches should take place.
If you find simple solution you can use this library
Example:
This code will replace $search to $replace in $pathToDocx file
$docx = new IRebega\DocxReplacer($pathToDocx);
$docx->replaceText($search, $replace);
Library phpoffice/phpword working is ok.
For correct working you must use the right symbols in your Word document, like that:
${name}
${lastname}
${officeAddress}
and for method "setValue" you need to use only names, like:
'name'
'lastname'
'officeAddress'
Very good working within Laravel, Lumen, and other frameworks
Example:
//This is the main document in Template.docx file.
$file = public_path('template.docx');
$phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);
$phpword->setValue('name','Santosh');
$phpword->setValue('lastname','Achari');
$phpword->setValue('officeAddress','Yahoo');
$phpword->saveAs('edited.docx');

jQuery / PHP - How to get random file in folder

I have my php code as follows:
<?php include("/myfolder/my-file-01.html"); ?>
and in the folder myfolder I have 2 files: my-file-01.html and my-file-02.html
Now, with jQuery or php, how can I randomly include my-file-01.html or my-file-02.html in one refresh my website (F5).
Any Idea?
Thanks
As an alternative, you could also load them inside an array thru scandir, point it into the files path, then use an array_rand:
$path_to_files = 'path/to/myfolder/';
$files = array_diff(scandir($path_to_files), array('.', '..'));
$file = $files[array_rand($files)];
require "$path_to_files/$file";
However, if you have other files other than my-file prefix, it'll get mixed up, so to prevent that from happening, you could use a glob solution instead. This will only search file/s that has that my-file prefix. Example:
$files = glob('myfolder/my-file-*.html');
$file = $files[array_rand($files)];
require $file;
You generate a random number which is 1 or 2 with the rand() function.
<?php
//Create random number 1 or 2:
$random = rand(1,2);
//Add zero before 1 or 2
$random = "0".$random;
//Include random file:
include("/myfolder/my-file-".$random.".html");

How to reference the current directory name, filename and file contents with RecursiveDirectoryIterator loop?

In the script below, I'm attempting to iterate over the folders and files inside of the $base folder. I expect it to contain a single level of child folders, each containing a number of .txt files (and no subfolders).
I'm just needing to understand how to reference the elements in comments below...
Any help much appreciated. I'm really close to wrapping this up :-)
$base = dirname(__FILE__).'/widgets/';
$rdi = new RecursiveDirectoryIterator($base);
foreach(new RecursiveIteratorIterator($rdi) as $files_widgets)
{
if ($files_widgets->isFile())
{
$file_name_widget = $files_widgets->getFilename(); //what is the filename of the current el?
$widget_text = file_get_contents(???); //How do I reference the file here to obtain its contents?
$sidebar_id = $files_widgets->getBasename(); //what is the file's parent directory name?
}
}
//How do I reference the file here to obtain its contents?
$widget_text = file_get_contents(???);
$files_widgets is a SplFileInfo, so you have a few options to get the contents of the file.
The easiest way is to use file_get_contents, just like you are now. You can concatenate together the path and the filename:
$filename = $files_widgets->getPathname() . '/' . $files_widgets->getFilename();
$widget_text = file_get_contents($filename);
If you want to do something funny, you can also use openFile to get a SplFileObject. Annoyingly, SplFileObject doesn't have a quick way to get all of the file contents, so we have to build a loop:
$fo = $files_widgets->openFile('r');
$widget_text = '';
foreach($fo as $line)
$widget_text .= $line;
unset($fo);
This is a bit more verbose, as we have to loop over the SplFileObject to get the contents line-by-line. While this is an option, it'll be easier for you just to use file_get_contents.

Inserting something at a particular line in a text file using PHP

I have a file called config.php, I want it to remain exactly as is, however on Line # 4 there is a line saying:
$config['url'] = '...could be anything here';
I'd like to only replace the contents of line # 4 with my own url provided for $config['ur'], is there a way to do this in PHP?
Since you know the exact line number, probably the most accurate way to do this is to use file(), which returns an array of lines:
$contents = file('config.php');
$contents[3] = '$config[\'url\'] = "whateva"'."\n";
$outfile = fopen('config.php','w');
fwrite($outfile,implode('',$contents));
fclose($outfile);
$myline = "my confg line";
$file = "config.php";
$contents = file($file);
$contents[3] = $myLine;
$file = implode("\n", $contents);
Either create another config (myconfig.php). Include the original and overwrite the option. include myconfig.php instead of the original one.
OR
Go to where config is included (you did use a single place for all your includes right?) and set the config option there.
include "config.php"
$config['url'] = "my_leet_urlz";
you could read the file, use str_replace or preg_replace on the appropriate strings, then write the file back to itself.
$filename = "/path/to/file/filename";
$configFile = file($filename);
$configFile[3] = '$'."config['url'] = '...could be anything here';";
file_put_contents($filename ,$configFile);
If there is only one $config['url'], use a preg_replace()
http://us.php.net/preg_replace
something like:
$pattern = '\$config['url'] = "[\d\w\s]*"'
$file_contents = preg_replace($pattern, $config['url'] = "my_leet_urlz";,$file_contents);
you'll need to fix the pattern as I'm new at regex and I know that's not right.

Categories