this is my first time posting.
I have a chat for a browser game, where people can send strings like this one:
Valentina stars a fight with Paul. She is using a [sword], a [shield], and a [dagger].
Now, what I want to achieve is to retrieve all the words within square brackets and create, for each of them, a link pointing to a modal window that shows the item description.
The code that I have is this one:
function gdrcd_chatcolor3($str) {
$search = [
'#\[(.*?)\]#'
];
$fullString = $chat_message;
$sTest = $str;
preg_match('#\[(.*?)\]#', $sTest, $aMatches);
$artefatto = $aMatches[1];
$caricaoggetto = gdrcd_query("SELECT * FROM oggetto WHERE oggetto.nome='".gdrcd_filter('get', $artefatto)."'");
$urloggetto= "javascript:modalWindow('oggetto', 'Oggetto', 'popup.php?page=popupitem&oggetto=". $caricaoggetto['id_oggetto'] ."', 800, 450);";
$replace = [
'<a href="' . $urloggetto . '"><span style="color: #c21616;">[$1]</span></a>',
];
return preg_replace($search, $replace, $str);
}
which kind of works.
I mean, it works for the first item, and I'm able to load the modal window with the id of the first item. But the second, third and so on, items, show all the same modalwindow.
I'm not a programmer. I understand that I have to create a kind of cicle or something like that, to make $urloggetto changes for each items.
So that the first item will load
popup.php?page=popupitem&oggetto=first item id;
second item will load
popup.php?page=popupitem&oggetto=scond item id
And so on.
Any help?
CodePudding user response:
Instead of using preg_match, you can use preg_replace_callback and do the replacement on the input $str for every match yielded by $aMatches.
The value of capture group 1 is in $aMatches[1]
For example:
function gdrcd_chatcolor3($str) {
return preg_replace_callback('#\[([^][]*)\]#', function($aMatches) {
$caricaoggetto = gdrcd_query("SELECT * FROM oggetto WHERE oggetto.nome='".gdrcd_filter('get', $aMatches[1])."'");
$urloggetto= "javascript:modalWindow('oggetto', 'Oggetto', 'popup.php?page=popupitem&oggetto=". $caricaoggetto['id_oggetto'] ."', 800, 450);";
return '<a href="' . $urloggetto . '"><span style="color: #c21616;">'.$aMatches[1].'</span></a>';
}, $str);
}
Note that you don't have to use intermediate strings and variables like
$fullString = $chat_message;
$sTest = $str;
