Replace a letter with multiple instances in a word once in php array

2 posts by 2 authors in: Forums > CMS Builder
Last Post: April 30, 2015   (RSS)

By gregThomas - April 30, 2015

Hey dm,

So you're trying to replace the first occurrence of a letter with the an input, then create a custom named input for each letter that gets replaced. I think this would be the easiest way to integrate this feature:

<?php

$word           = "diplodocus";  //The word we're testing the user on.
$replaceLetters = array('p', 'o'); //The letters we're going to replace.
$wordArray      = str_split($word); //This function will turn a string into an array, eg: array('d', 'i', 'p', 'l' etc.

//Cycle through the letters in our word.
foreach($wordArray as $letter){

  //If the letter is in our replace letters array, add it's key to the key variable and enter the if statement...
  if(($key = array_search($letter, $replaceLetters)) !== false){

    //Output the input, use the key as the unique identifier.
    echo "<input type=\"text\" name=\"question_1_letter_$key\" class=\"inputs\" maxlength=\"1\" value=\"\" />";

    //Remove this value from the replaceLetters array, as we've now set it.
    unset($replaceLetters[$key]);

  //If the letter isn't in the array, then display it.
  }else{
    echo $letter;
  }
}

?>

I've used the key value from the $replaceLetters array as the unique key value for the input. The advantage of this is that when the user submits the form it will be easier to detect if the user has entered the correct value or not. 

Let me know if you have any questions about how this code works, or how to integrate it.

Cheers,

Greg

Greg Thomas







PHP Programmer - interactivetools.com