I am working on a notification system for a game i'm working on.
I decided to store messages as a string with 'variables' set up to be replaced by the data received through an array.
Example of the message:
This notification will display !num1 and also !num2
The array I receive from my query will look like:
[0] => Array
(
[notification_id] => 1
[message_id] => 1
[user_id] => 3
[timestamp] => 2013-02-26 09:46:20
[active] => 1
[num1] => 11
[num2] => 23
[num3] =>
[message] => This notification will display !num1 and also !num2
)
What I want to do is replace !num1 and !num2 with the values from the array (11, 23).
message is INNER JOINed in a query from the message_tbl
. I suppose the tricky part is num3
which is stored as null.
I am trying to store all notifications for all different types of messages in only 2 tables.
Another example would be :
[0] => Array
(
[notification_id] => 1
[message_id] => 1
[user_id] => 3
[timestamp] => 2013-02-26 09:46:20
[active] => 1
[num1] => 11
[num2] => 23
[num3] =>
[message] => This notification will display !num1 and also !num2
)
[1] => Array
(
[notification_id] => 2
[message_id] => 2
[user_id] => 1
[timestamp] => 2013-02-26 11:36:20
[active] => 1
[num1] =>
[num2] => 23
[num3] => stringhere
[message] => This notification will display !num1 and also !num3
)
Is there a way in PHP to successfully replace the !num(x) with the correct value in the array?
You can do this with a regular expression and a custom callback, like this:
$array = array( 'num1' => 11, 'num2' => 23, 'message' => 'This notification will display !num1 and also !num2');
$array['message'] = preg_replace_callback( '/!\b(\w+)\b/', function( $match) use( $array) {
return $array[ $match[1] ];
}, $array['message']);
You can see from this demo that this outputs:
This notification will display 11 and also 23
Here:
$replacers = array(11, 23);
foreach($results as &$result) {
foreach($replacers as $k => $v) {
$result['message'] = str_replace("!num" . $k , $v, $result['message']);
}
}