Page 1 of 1

String replace

Posted: Thu Aug 24, 2006 9:52 am
by SteveB
I have a string that could contain one or more substrings of the form $(bla). I have several rows of a database in which I need to run against this master string, changing the $(bla) to the value of the bla field for that row in the database, thus producing a series of output URLs.

I'm using this pattern to find the substr: \$\((\w+)\) and I want then to replace it with $row['bla'], with this happening once per row of the database results. But what function can handle this? It seems the regex functions only want strings for the pattern and replacement, so they won't work.

The only thing I can think of is using an array of search and replacements, one for each column in the database and then running it over the string. So I am basically checking every database field on every row, which seems like a lot of work, given that only 1 field or even none may need to be replaced. (See example 2)

Any ideas?

Thanks.

Posted: Thu Aug 24, 2006 10:18 am
by feyd
preg_replace_callback() maybe? Although I'm sure someone will pipe in with "use the e modifier"; which isn't the best of ideas due to the security hole it creates.

Posted: Thu Aug 24, 2006 10:48 am
by onion2k
Take the string, convert $(bla) to $row['bla'], and then do $string = eval("return $string"); it to do the substitutions. :)

Posted: Thu Aug 24, 2006 11:02 am
by feyd
That's just as bad as the "use e modifier" :P

Posted: Thu Aug 24, 2006 11:04 am
by SteveB
I've been trying to use this callback, but for some silly reason it isn't actually calling the callback method. Although if you ommit the method, it will complain.

Code: Select all

//$setup['action'] = http://localhost:8080/oop/test.php?id=$(MessageID)

function replaceVars($matches) {
	return "Steve";
}

echo preg_replace_callback("|\$\((\w+)\)|", "replaceVars", $setup['action']);

// Ouput = http://localhost:8080/oop/test.php?id=$(MessageID)
Am I going crazy or is it not calling the method?

Posted: Thu Aug 24, 2006 11:07 am
by feyd
Are you sure the pattern is correct? preg_match() can show you that.

Posted: Thu Aug 24, 2006 11:16 am
by SteveB
Ok, apparently it didn't like the \$ at the start, but even after removing that, why does the it output:

http://localhost:8080/oop/test.php?id=$Steve

and not just:

Steve

?

Edit: I'm getting very confused where I'm going with this now...

Posted: Thu Aug 24, 2006 11:24 am
by feyd
Try switching your pattern to

Code: Select all

'#\\$\\((\\w+)\\)#'

Code: Select all

[feyd@home]>php -r "$p = '#\\$\\((\\w+)\\)#'; $s = 'http://localhost:8080/oop/test.php?id=$(MessageID)'; preg_match($p, $s, $m); var_dump($m);"
array(2) {
  [0]=>
  string(12) "$(MessageID)"
  [1]=>
  string(9) "MessageID"
}
Also, you should be aware that \w matches more than alphanumeric characters. See here: viewtopic.php?p=245010#245010