1

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?

6 Answers 6

6

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);
Sign up to request clarification or add additional context in comments.

Comments

2
$myline = "my confg line";

$file = "config.php";

$contents = file($file);
$contents[3] = $myLine;
$file = implode("\n", $contents);

Comments

1

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";

Comments

0

you could read the file, use str_replace or preg_replace on the appropriate strings, then write the file back to itself.

Comments

0
$filename = "/path/to/file/filename";
$configFile = file($filename);
$configFile[3] = '$'."config['url'] = '...could be anything here';";
file_put_contents($filename  ,$configFile);

Comments

0

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.

Comments

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.