echo php within preg_replace to allow database update?

4 posts by 2 authors in: Forums > CMS Builder
Last Post: May 22, 2014   (RSS)

By dm - May 13, 2014

Hi all,

I am using cms builder to make a kind of vocabulary hangman type game... using php preg_replace to remove random letters from words stored in the cms database and replacing them with text input fields which when the users enter what they think the missing letter is should be which are then submitted to my mysql database for checking as per the addform.php example found on this forum.

I am rather lost on how to convert the input "value" to echo php code needed to import the letter to my cms db...

In my php file I have the following:

<? echo preg_replace("/$selected_letter/", "<input type=\"text\" class=\"inputs\" maxlength=\"1\" value=\"\" />", $str); ?>

This echoes out into my page with no problems:

<input type="text" class="inputs" maxlength="1" value="" />

What I really need to echo is the following (as per the addform.php):

<input type="text" class="inputs" maxlength="1" value="<?php echo htmlspecialchars(@$_REQUEST['test']) ?>" />

Doing the following doesn't works as I am unable to echo <?php echo htmlspecialchars(@$_REQUEST['test']) ?> within the preg_replace echo if that makes sense...

<? echo preg_replace("/$selected_letter/", "<input type=\"text\" class=\"inputs\" maxlength=\"1\" value=\"<?php echo htmlspecialchars(@$_REQUEST['test']) ?>\" />", $str); ?>

I would greatly appreciate it if someone more skilled in php could point me in the right direction as to how/if I can acheive this? Maybe preg_replace is not the answer here but I have spent many days searching and not found a closer alternative so far..

Many Thanks!

By gregThomas - May 16, 2014

Hi dm,

I notice that your input doesn't have a name attribute, could the issue be that when you submit the form the value isn't being passed because no name has been set in the input? Changing the input to the following should create $_REQUEST['test'] when the form is submitted:

<input type="text" class="inputs" name="test" maxlength="1" value="<?php echo htmlspecialchars(@$_REQUEST['test']) ?>" />

Does that resolve the issue?

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

By dm - May 22, 2014

Just in case anyone else is looking for a similar solution in the future here is the code I found which works for allowing various replacements... 

$string = $selected_word;
$Find = Array($selected_letter, $selected_letter2, $selected_letter3);
$Replace = Array("<input type=\"text\" name=\"one\" class=\"inputs\" maxlength=\"1\" value=\"\" />", "<input type=\"text\" name=\"two\" class=\"inputs\" maxlength=\"1\" value=\"\" />", "<input type=\"text\" name=\"three\" class=\"inputs\" maxlength=\"1\" value=\"\" />");

$New_string = strtr($string, array_combine($Find, $Replace));

echo $New_string;

Cheers!