Find and replace for files PHP.

Echo89

A little find and replace function for PHP, not tested, but theoretically should work.

1,728 Views
About the Author
function find_replace($find, $replace, $file, $case_insensitive = true)
{
	if(!file_exists($file))
	{
		return false;
	}
	else
	{
		$contents = file_get_contents($file);
		if($case_insensitive)
		{
			$output = str_ireplace($find, $replace, $contents);
		}
		else
		{
			$output = str_replace($find, $replace, $contents);
		}
		
		$fopen = fopen($file, 'w');
		if(!$fopen)
		{
			return false;
		}
		else
		{
			$fwrite = fwrite($fopen, $output);
			if(!$fwrite)
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		fclose($open);
	}
}
pritaeas 2,045 Most Valuable Poster Moderator Featured Poster

not tested, but theoretically should work

This alone made me want to hit the vote down button, but I refrained ;) It's an acceptable start.
"In theory, theory and practice are the same. In practice, they’re not."

Room for improvements (IMHO):

  • Returning false is a little weird, you still do not know what's wrong. An exception would provide more information.
  • Why do you use file_get_contents but not file_put_contents ?
  • Returning the number of replacements is more useful than just true.
  • Regular expression search/replace would be useful.
commented: file_put_contents() ... he missed it :) +0
Echo89 9 Web Developer

Thank you, I will update this when I get the time.

coreyavis 13 Dev Poster

fclose($open); should be fclose($fopen);.

CodeAngry 11 Newbie Poster
<?php
/**
* Replace stuff in a file.
* 
* @throws InvalidArgumentException if $file is not a proper string
* @param path $file
* @param string $find
* @param string $replace
* @param bool $case_insensitive
* @return bool
*/
function find_replace($file, $find, $replace, $case_insensitive = true){
    // Validate arguments
    if(!is_string($file) or !strlen($file = trim($file))){
        throw new InvalidArgumentException('$file must be a non-empty trimmed string.');
    }

    // File not found
    if(!file_exists($file)) return false;

    // Empty so... no work here (but still a success)
    if(!filesize($file)) return true;

    // Fetch file contents
    $contents = file_get_contents($file);

    // Replacements go here
    $output = call_user_func_array($case_insensitive ? 'str_ireplace' : 'str_replace', $find, $replace, $contents);

    // Did we succeed?
    return (bool)file_put_contents($file, $output, LOCK_EX);
}

/**
* Case-insensitive alias of find_replace().
* 
* @param path $file
* @param string $find
* @param string $replace
* @return bool
*/
function find_ireplace($file, $find, $replace){
    return find_replace($file, $find, $replace, false);
}
?>

A rewrite of this slightly useless snippet. Shorter and more to the point.

Not to mention that the OP leaves the handle of the file open with his imbricated if else madness.

Once you return, you're out. No need to keep elsing after a return. Argh...

Echo89 9 Web Developer

@CodeAngry...

The arrogance emanating from your post is suffocating.

To be honest I think your name matches your posts content.

Do me and everyone else a favour, shut up. If you don't like what I posted, don't be so negative about it. Simply point out my mistakes, and recommend ways of improving them like pritaeas has done (And that means not being so arrogant).

Besides, this was six months ago. I've learned a lot in that time. I've moved on to more serious projects.

CodeAngry commented: I'm not arrogant... just to the point. +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.