YourNameHere Posted August 11, 2010 Share Posted August 11, 2010 Hi, I am trying to take a string from a database and replace everything within {} with code... similar to how posting in a forum works. so say I have "...Lorem ipsom {gallery:1} sit imet..." it will take that string (from a DB) and replace "{gallery:1}" with "<?php gallery('1'); ?>". How can this be done? Or is there keywords I can search on to find the answer? Thank you in advance. Link to comment https://forums.phpfreaks.com/topic/210468-replace-text-in-string-with-php-code/ Share on other sites More sharing options...
wildteen88 Posted August 11, 2010 Share Posted August 11, 2010 You'll want to use regex, an example function gallery($id) { return "[sHOW GALLERY ID: $id]"; } $str = '...Lorem ipsom {gallery:1} sit imet...'; $str = preg_replace('~\{gallery:([0-9]+)\}~ies', 'gallery($1)', $str); echo $str; Link to comment https://forums.phpfreaks.com/topic/210468-replace-text-in-string-with-php-code/#findComment-1098215 Share on other sites More sharing options...
YourNameHere Posted August 11, 2010 Author Share Posted August 11, 2010 Thank you, that worked! Now to figure out how to extend that with the gallery: part being variable. ie. [a-z]/ $1. You rock! Link to comment https://forums.phpfreaks.com/topic/210468-replace-text-in-string-with-php-code/#findComment-1098224 Share on other sites More sharing options...
YourNameHere Posted August 14, 2010 Author Share Posted August 14, 2010 Everything in the exec' function (echo or otherwise) gets placed above the entire string when echoed. is there a workaround for this? the gallery() function requires in a template.php that prints the javascript image gallery to the page and a button that opens the gallery. but the button is above the string on the page. Is this an expected side effect of the require? Link to comment https://forums.phpfreaks.com/topic/210468-replace-text-in-string-with-php-code/#findComment-1099117 Share on other sites More sharing options...
wildteen88 Posted August 14, 2010 Share Posted August 14, 2010 Post your code here. I think the issue maybe with you using echo within the function. You should instead save all output within the function to a temporary variable and the use return. Link to comment https://forums.phpfreaks.com/topic/210468-replace-text-in-string-with-php-code/#findComment-1099157 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.