Patrik Patrik - 6 months ago 43
PHP Question

Regex match WordPress wp-config configurations

I'm trying to replace some content in the wp-config with regex but I can't get it to work.

Here is my regex pattern:

(?=DB_NAME', ')(.*?)(?<='\);)


And here is a snippet of the config:

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'database_name_here');

/** MySQL database username */
define('DB_USER', 'username_here');


The idea is to replace database_name_here.

And the php:

$configContent = preg_replace("/(?=DB_NAME', ')(.*?)(?<='\);)/", $databaseName, $configContent);


The result is this:

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('database-name

/** MySQL database username */
define('DB_USER', 'username_here');


So the pattern doesnt work. But I don't know how to fix it. Why is the lookarounds included in the group?

The reason I don't use str_replace and replace database_name_here is because I will use this in multiple languages. And database_name_here is translated in other languages.

Answer

You have swapped the order of look-ahead and look-behind.

"/(?=DB_NAME', ')(.*?)(?<='\);)/"

should be:

"/(?<=DB_NAME', ')(.*?)(?='\);)/"
Comments