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.
String replace
Moderator: General Moderators
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.
Am I going crazy or is it not calling the method?
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)- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Are you sure the pattern is correct? preg_match() can show you that.
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...
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...
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Try switching your pattern to
Also, you should be aware that \w matches more than alphanumeric characters. See here: viewtopic.php?p=245010#245010
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"
}