hice3000
hice3000

Reputation: 186

How to find and replace a line in multiple files with PHP

I want to create a installer for my current project, that automatically modifies a dozens of config files.

So if the form was sent, the PHP script should look in which config file the searched option is and change it. Before you ask, I cant put the files together ;) .

A basic config line looks like this: $config['base_url'] = 'test';. I tried to use str_replace()but this didn't work because I don't know what is currently in the variable.

So I need a function that searches for $config['base_url'] = '%'; in multiple files and replaces it with $config['base_url'] = 'new_value'; (for example).

Upvotes: 1

Views: 222

Answers (2)

Crisp
Crisp

Reputation: 11447

I realise the answer's accepted, and originally I deleted this, however, in the comments you mention the config being editable, which presumably means by other users, so you can't guarantee the spacing will match, nor that they'll use ' instead of " always, so the following is perhaps a little more forgiving

$name = 'base_url';
$value = 'new_value';
$config = '$config["base_url"] = "old_value";';

$config  = preg_replace('/\[(?:\'|\")'.$name.'(?:\'|\")\]\s*=\s*(\'|\")(.*)\\1;/', "['".$name."'] = '$value';", $config);

echo '<pre>', var_dump($config), '</pre>';

Upvotes: 2

Appleshell
Appleshell

Reputation: 7388

You can use a regular expression like the following:

/\$config\['base_url'\] = '[a-zA-Z0-9]';/

Which you would have to adapt to each line.

A better solution, in my opinion, would be to create a template config file with lines like the following:

$config['base_url'] = '%BASE_URL%';

Where you could simply use str_replace().

Upvotes: 0

Related Questions