Solved

PHP/REGEX: find/replace values from array

Posted on 2009-05-15
10
1,305 Views
Last Modified: 2012-08-14
Hello,

I want to use PHP/REGEX to find and replace in $config old values with new values.

My new values are in an array:

$newValues = array('type'=> 'FlatFile', 'type'=> 'FlatFile', 'server'=> '22.22.22.22', 'username'=> 'justme');

My old values are in this format:
      "type" => "MySQLDatabase",
      "server"=>"localhost",
      "username" => "myname",
      "password"    =>  "mypass",
      "database"       =>     "mydb",


So for each item in the array I need to find the old value and replace it with the new.


$newValues = array('type'=> 'FlatFile', 'type'=> 'FlatFile', 'server'=> '22.22.22.22', 'username'=> 'justme');
 
/// This:
	"type" => "MySQLDatabase",
	"server"=>"localhost", 
	"username" => "myname", 
	"password"    =>  "mypass", 
	"database"	 =>     "mydb",
 
// Should be updated to become this:
	"type" => "FlatFile",
	"server"=>"22.22.22.22", 
	"username" => "justme", 
	"password"    =>  "mypass", 
	"database"	 =>     "mydb",

Open in new window

0
Comment
Question by:hankknight
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 80 total points
ID: 24399185
I would use a foreach iterator to do this.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24399204

<?php // RAY_temp_hank.php
error_reporting(E_ALL);
 
// FROM THE OP
$newValues = array('type'=> 'FlatFile', 'type'=> 'FlatFile', 'server'=> '22.22.22.22', 'username'=> 'justme');
 
// OLD ARRAY
$old = array(
        "type" => "MySQLDatabase",
        "server"=>"localhost",
        "username" => "myname",
        "password"    =>  "mypass",
        "database"       =>     "mydb"
    );
 
// COPY ARRAY
$new = $old;
 
// REPLACE VALUES
foreach ($newValues as $key => $val)
{
    $new[$key] = $val;
}
 
// SHOW INPUT AND OUTPUT
echo "<pre>\n";
var_dump($old);
var_dump($new);

Open in new window

0
 
LVL 1

Assisted Solution

by:dreamluverz
dreamluverz earned 20 total points
ID: 24412019
here's a nice guide in using regex and php http://dreamluverz.com/developers-tools/regex/regex
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 27

Expert Comment

by:ddrudik
ID: 24413874
hankknight, ray seemed to have it, did that work for you?
0
 
LVL 16

Author Comment

by:hankknight
ID: 24419925
Thank you all for your comments.  Ray's idea is not what I am looking for.  Perhaps I did not write my question clearly.  

$config is a STRING and not a PHP script.  So regex is needed.

My code below demonstrates what I am looking for.  It requires the kind of regex that ddrudik creates in his sleep.
<?php
 
$config_code = ' 
	"type" => "MySQLDatabase",
	"username" => "myname", 
	"database"	 =>     "mydb",
	"server"=>"localhost", 
	"password"    =>  "mypass", 
';
 
$newValues = array('type'=> 'FlatFile', 'type'=> 'FlatFile', 'server'=> '22.22.22.22', 'username'=> 'justme');
 
foreach ($newValues as $key => $val) {
   $config_code = preg_replace('Find the corsponding values of $key)', $val, $config_code);
}
 
file_put_contents('new_config.php', $config_code);
 
?>

Open in new window

0
 
LVL 27

Accepted Solution

by:
ddrudik earned 400 total points
ID: 24420325
For that you might consider:
   $config_code = preg_replace("/(\"$key\"(?:(?!=>).)*)=>([^,]*)/","$1 => \"$val\"",$config_code);

Open in new window

0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 24420608
If you are on PHP 5.3.0, then here is a working method using closures. Ok. This is me showing off. Personally a simple foreach() loop would have been fine.



<?php
$config_code = '
        "type" => "MySQLDatabase",
        "server"=>"localhost", 
        "username" => "myname", 
        "password"    =>  "mypass", 
        "database"       =>     "mydb",
';
 
$wanted_code = '
        "type" => "FlatFile",
        "server"=>"22.22.22.22", 
        "username" => "justme", 
        "password"    =>  "mypass", 
        "database"       =>     "mydb",
';
 
$newValues = array
	(
	'type'     => 'FlatFile',
	'type'     => 'FlatFile',
	'server'   => '22.22.22.22',
	'username' => 'justme',
	);
 
array_walk
	(
	$newValues,
	function($Value, $Key) use(&$config_code)
		{
		$config_code = preg_replace
			(
			"`\"{$Key}\"(\s*=>\s*)\"[^\"]+\",`",
			"\"{$Key}\"\\1\"{$Value}\",",
			$config_code
			);
		}
	);
 
/* array_map variant */
/*array_map(
	function($Value, $Key) use(&$config_code)
		{
		$config_code = preg_replace
			(
			"`\"{$Key}\"(\s*=>\s*)\"[^\"]+\",`",
			"\"{$Key}\"\\1\"{$Value}\",",
			$config_code
			);
		},
	$newValues,
	array_keys($newValues)
	);
*/	
echo $config_code, PHP_EOL;
 
echo $config_code === $wanted_code ? 'Matches' : 'Different';
// file_put_contents('new_config.php', $config_code);

Open in new window

0
 
LVL 16

Author Comment

by:hankknight
ID: 24420898
RQuadling, interesting idea but to comlicated for me right now.

ddrudik, once again you have created perfect regex.  
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 24421139
Of course. The foreach() loop is fine. Just showing off and hopefully giving those that are on the cutting edge of PHP a little extra.
0
 
LVL 27

Expert Comment

by:ddrudik
ID: 24422270
Thanks for the question and the points.

Here's another option for those seeking an alternative PHP solution (still not preferred over the regex method given the lack of security inherent to eval):
<pre>
<?php
 
$config_code = ' 
	"type" => "MySQLDatabase",
	"username" => "myname", 
	"database"	 =>     "mydb",
	"server"=>"localhost", 
	"password"    =>  "mypass", 
';
 
$newValues = array('type'=> 'FlatFile', 'type'=> 'FlatFile', 'server'=> '22.22.22.22', 'username'=> 'justme');
eval("\$oldValues=array($config_code);");
foreach ($newValues as $key => $val) {
     $oldValues[$key] = $val;
}
 
echo print_r($oldValues,true);
?>

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ajax to record click 3 16
check mysql insert 12 28
Generate PDF from MySQL using PHP 3 26
How to get this library to work load? 8 25
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question