Jump to content

fopen and pref_replace()? - need to do a find & replace in multiple files...


nikefido

Recommended Posts

Hey - I was wondering what the procedure was for opening a file and then doing a find and replace (preg_replace?) to each file.

 

Not asking you to write the code, I can do that, but I'm not sure if i can FIND a certain string that's in the file and then replace it with another string?

 

Thanks!

 

(i can supply my code so far, but it doesn't have anything with this problem of it, it's just the recursive function to go through the file directory.)

 

Do I have to use file_get_contents() ?

Link to comment
Share on other sites

yup...i would would use file_get_contents() to put it in a variable, use preg_replace() to do your manipulation of the variable, then file_put_contents() to write it back to the file. Then put that code inside your loop that goes over each file.

Link to comment
Share on other sites

yup...i would would use file_get_contents() to put it in a variable, use preg_replace() to do your manipulation of the variable, then file_put_contents() to write it back to the file. Then put that code inside your loop that goes over each file.

so i need to get all the contents (file_get_contents();), then delete all the contents( ftruncate($handle, 0); ), then put them back(file_put_contents();)

 

I assume I should truncate it just to be sure.

 

What about formatting of the file (they are html pages)? Will it write it back as all one line?

Link to comment
Share on other sites

that all depends if file_get_contents can fit the file into memory. if not ya will prolly end up doing file chunking, reading a chunk of the file checking it, than cycle until eof.

 

 

they are all .html or .htm files that will be read - they will not be too large in length..

 

 

Here is a bit of my (pseudo) code. Do I need to use fopen with file_get_contents and such?

Am I using file_put_contents correctly? These files that I am reading through will all be local...

 

$file_extension = strtolower(substr(strrchr($filename,"."),1));
if(strcmp($file_extension, 'htm')==0 || strcmp($file_extension, 'html')==0) {
	//if TRUE, find </body> and replace with snippet
	$content=file_get_contents("$file",FALSE,NULL,0,20);
	preg_replace($pattern, $replacement, $content);
	file_put_content($filepath, $snippet, FALSE, NULL);
}

Link to comment
Share on other sites

a little simpler...

 

<?php
  if(substr($fileName,-4) == '.htm' || substr($fileName,-5) == '.html'){
    //if TRUE, find </body> and replace with snippet
    $content = preg_replace($pattern, $replacement, file_get_contents($fileName));
    file_put_contents($fileName, $content);
  }
?>

Link to comment
Share on other sites

in that case, you str_replace

 

<?php
  $text = "This is the text I want to add";
  if(substr($fileName,-4) == '.htm' || substr($fileName,-5) == '.html'){
    //if TRUE, find </body> and replace with snippet
    $content = str_replace('</body>',$text.'</body>', file_get_contents($fileName));
    file_put_contents($fileName, $content);
  }
?>

Link to comment
Share on other sites

It's not working - output doesn't replace </body> with my string! wtf!

output:

my string with </body>

<?php

function readIt($start_dir='.') {

if (is_dir($start_dir)) {
	$fh = opendir($start_dir);
	while (($file = readdir($fh)) !== false) {
		// loop through the files, skipping ".", "..", ".DS_Store", and ".htaccess" then recursing if necessary
		if (strcmp($file, '.')==0 || strcmp($file, '..')==0 || strcmp($file, ".DS_Store")==0 || strcmp($file, ".htaccess")==0) continue;
		$filepath = $start_dir . '/' . $file;
		if ( is_dir($filepath) ) {
			readIt($filepath); //run recursively if a directory
		} else {
			//test for .htm or .html
			$file_extension = strtolower(substr(strrchr($file,"."),1));
			if(strcmp($file_extension, 'htm')==0 || strcmp($file_extension, 'html')==0) {
				echo "<p>" . $filepath . "</p>"; //want to know filepath of all .htm/.html files
				//if TRUE, find </body> and replace with code snippet
				$content = str_replace('</body>', $snippet.'</body>', 'my string with </body>'/*file_get_contents($filepath)*/);
    					//file_put_contents($filepath, $content);
				echo $content;
			}
		}
	}//end while
	closedir($fh);
	echo "<p>PROCESS COMPLETE</p>";
} else {
	echo "Valid directory not supplied or improper file permissions set";
}//endif(is_dir)
}//end function


$dir = "/Users/Chris/Sites/_resources"; //directory to start

$snippet = "my stuff";
readIt($dir);
?>

Link to comment
Share on other sites

yup, the function can't see the snipper variable. the proper way is to pass that variable as an argument.

 

<?php

function readIt($start_dir='.',$snippet='') {

if (is_dir($start_dir)) {
	$fh = opendir($start_dir);
	while (($file = readdir($fh)) !== false) {
		// loop through the files, skipping ".", "..", ".DS_Store", and ".htaccess" then recursing if necessary
		if (strcmp($file, '.')==0 || strcmp($file, '..')==0 || strcmp($file, ".DS_Store")==0 || strcmp($file, ".htaccess")==0) continue;
		$filepath = $start_dir . '/' . $file;
		if ( is_dir($filepath) ) {
			readIt($filepath,$snippet); //run recursively if a directory
		} else {
			//test for .htm or .html
			$file_extension = strtolower(substr(strrchr($file,"."),1));
			if(strcmp($file_extension, 'htm')==0 || strcmp($file_extension, 'html')==0) {
				echo "<p>" . $filepath . "</p>"; //want to know filepath of all .htm/.html files
				//if TRUE, find </body> and replace with code snippet
				$content = str_replace('</body>', $snippet.'</body>', 'my string with </body>'/*file_get_contents($filepath)*/);
    					//file_put_contents($filepath, $content);
				echo $content;
			}
		}
	}//end while
	closedir($fh);
	echo "<p>PROCESS COMPLETE</p>";
} else {
	echo "Valid directory not supplied or improper file permissions set";
}//endif(is_dir)
}//end function


$dir = "/Users/Chris/Sites/_resources"; //directory to start

$snippet = "my stuff";
readIt($dir,$snippet);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.