0

I am using this function to replace strings in a file:

function replace_in_file($FilePath, $OldText, $NewText)
{
    $Result = array('status' => 'error', 'message' => '');
    if(file_exists($FilePath)===TRUE)
    {
        if(is_writeable($FilePath))
        {
            try
            {
                $FileContent = file_get_contents($FilePath);
                $FileContent = str_replace($OldText, $NewText, $FileContent);
                if(file_put_contents($FilePath, $FileContent) > 0)
                {
                    $Result["status"] = 'success';
                }
                else
                {
                   $Result["message"] = 'Error while writing file';
                }
            }
            catch(Exception $e)
            {
                $Result["message"] = 'Error : '.$e;
            }
        }
        else
        {
            $Result["message"] = 'File '.$FilePath.' is not writable !';
        }
    }
    else
    {
        $Result["message"] = 'File '.$FilePath.' does not exist !';
    }
    return $Result;
}

the problem is this: I have a lot of similar words in my file. so when I change one of them all of them changes. what should I do to change only that I want?

myfile.php:

define("word1","string");
define("word2","string");
define("word3","string");
...

(How to change for example string value in word1 without changing strings in others?)

2
  • It would have helped if you included examples of how it does not work and what you expect it to do instead. Commented Feb 5, 2017 at 17:58
  • for example I want to change "string" value of word1, I use function like this: $oldtext = "string"; $newtext = "something new!"; replace_in_file($filepath,$oldtext,$newtext); ............ But when I execute this all of string values changed to "something new!" ! I just want to word1 value's to be changed. I hope this helped :) Commented Feb 5, 2017 at 19:55

1 Answer 1

1

There are a couple approaches you could take. Two I'll show here rely on the regular data structure you have indicated in your example file contents.

Rather than replacing the term "string" you could replace the term ("word1","string") keeping most of that substring the same but changing only the string portion.

Something like:

$fileContents = '
define("word1","string");
define("word2","string");
define("word3","string");
';

$oldText = '("word1","string")';
$newText = '("word1","NewString")';

$fileContents = str_replace($oldText,$newText,$fileContents);

echo $fileContents;

Another option is to search for "word1" or another search term, and replace a substring just after it (3 characters after it if your replacement term is separated from your search term by ",":

// File contents based on question text:
$fileContents = '
define("word1","string");
define("word2","string");
define("word3","string");
';

// Word to search for:
$searchWord = 'word1';
// Replacement text for that line:
$newText = "someNewText";


// to determine the length between the search term and the replacement term.
$seperator = '","';


// Get beginning position of the search string
if( $position = strpos($fileContents,$searchWord.$seperator) ) {

    // Where the word to be replaced starts:
    $start = $position + strlen($searchWord.$seperator);

    // length of the term to be replaced:
    $length = strlen("string");

    // do the actual replacements:
    $fileContents = substr_replace($fileContents,$newText,$start,$length);

}

echo $fileContents;

I've put both approaches into a php sandbox: approach 1, approach 2.

Sign up to request clarification or add additional context in comments.

1 Comment

thank u. I used first solution and it worked very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.