Home > OS >  PHP Foreach loop returns result twice
PHP Foreach loop returns result twice

Time:05-17

I am trying to generate a fill-in-the-blank text with php where the parts to be filled are stored in my SQL database with curly brakets.

Fore example:

7 5 10 7 21 17 68 {63} {315}

{63} and {315} should be replaced by inputs type text with size="2" for the first and size="3"for the second one.

I created a regex (thanks to SO) and the preg_match_all function returns an Array with the identified values.

$chapitre_name = "7 5 10 7 21 17 68 {63} {315}";
$regex = '~\{([^}]*)\}~';
preg_match_all($regex, $chapitre_name, $matches);
var_dump($matches[1]);

Returns the array:

array (size=2)
  0 => string '63' (length=2)
  1 => string '315' (length=3)

Then to replace those values I created a foreach loop to calculate the length and create an input for each value.

$input = '';
foreach($matches[1] as $key=>$value_resultat ) {
    $length = strlen($value_resultat);
    $input .= '<input type="text" name="'.$chapitre_id.'[]" value="'.$value_resultat.'" size="'.$length.'" />';
}
$chapitre_name = preg_replace($regex,$input,$chapitre_name);

(Obviously the value ="'.$value_resultat.'" is only for debugging purpose.)

My problem is when I echo '<p>'.$chapitre_name.'</p>';, each field is repeated twice. Eg.

<p>7 5 10 7 21 17 68 <input type="text" name="646" value="63" size="2"><input type="text" name="646" value="315" size="3"> <input type="text" name="646" value="63" size="2"><input type="text" name="646" value="315" size="3"></p>

As a precision, the fill in the blank text could contain any type of text or digit, on any length and there can be as much blank fields as needed per the Administrator who creates the quizz.

CodePudding user response:

You can use preg_replace_callback as approach:

$chapitre_name =  preg_replace_callback(
    $regex,
    function($matches) use($chapitre_id) {
        return '<input type="text" name="'.$chapitre_id.'" value="'.$matches[1].'" size="'.strlen($matches[0]).'" />';
    },
    $chapitre_name
);

echo $chapitre_name;

Test preg_replace_callback

or using short syntax with arrow function and sprintf:

$chapitre_name =  preg_replace_callback(
    $regex,
    fn($matches) => sprintf(
        '<input type="text" name="%s" value="%s" size="%d" />',
        $chapitre_id,
        $matches[1],
        strlen($matches[0])
    ),
    $chapitre_name
);
  •  Tags:  
  • php
  • Related