0

I am trying to use a str_replace in this. When i use a array("","") it works and replaces as required, however when i use a predefined array, in this case fetched from a my_sql database it dosnt seem to work. Also the str_replace works with the predefined arrays outside the preg_replace_callback()

<?
$Starting_word = array();
$Finishing_word = array();
$con = mysqli_connect("localhost","root","root","Words");
$getmodels = mysqli_query($con, "SELECT * FROM Words");
while($res = mysqli_fetch_assoc($getmodels)) {
$Starting_word[] = $res['1'];
$Finishing_word[] = $res['2'];
}
$string = '<html><h1> some hello  text i want to replace</h1><p>
some stuff i want to replace </p>';
$text_to_echo =  preg_replace_callback(
"/(<([^.]+)>)([^<]+)(<\\/\\2>)/s", 
function($matches){
    /*
     * Indexes of array:
     *    0 - full tag
     *    1 - open tag, for example <h1>
     *    2 - tag name h1
     *    3 - content
     *    4 - closing tag
     */
    //print_r($matches);
    $text = str_replace($Starting_word, $Finishing_word, $matches[3]);
    return $matches[1].$text.$matches[4];
}, 
$string
);
echo $text_to_echo;
?>

I have tried changing to mysqli_fetch_array and it made no change. Thanks.

PHP9274745382389
  • 169
  • 2
  • 14
  • There is a commented out `print_r` in there. What does it return? PHP doesn't know or care where the array comes from, so the only explanation is that it contains a different format or data than the hardcoded array you tried earlier, or your previous test was incorrect as @MarkBaker's answer suggests as well. – GolezTrol Nov 24 '13 at 17:35

1 Answers1

1

Unless you pass $Starting_word and $Finishing_word to the callback function using use they are out of scope in the callback

Try

$Starting_word = array();
$Finishing_word = array();
$con = mysqli_connect("localhost","root","root","Words");
$getmodels = mysqli_query($con, "SELECT * FROM Words");
while($res = mysqli_fetch_assoc($getmodels)) {
    $Starting_word[] = $res['1'];
    $Finishing_word[] = $res['2'];
}
$string = '<html><h1> some hello  text i want to replace</h1><p>
some stuff i want to replace </p>';
$text_to_echo =  preg_replace_callback(
    "/(<([^.]+)>)([^<]+)(<\\/\\2>)/s", 
    function($matches) use ($Starting_word, $Finishing_word) {
        /*
         * Indexes of array:
         *    0 - full tag
         *    1 - open tag, for example <h1>
         *    2 - tag name h1
         *    3 - content
         *    4 - closing tag
         */
        //print_r($matches);
        $text = str_replace($Starting_word, $Finishing_word, $matches[3]);
        return $matches[1].$text.$matches[4];
    }, 
    $string
);
echo $text_to_echo;
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Thanks, this works but when i have tried to use this using : file_get_contents it doesnt seem to change words over the whole document, but in random select tags. – PHP9274745382389 Nov 24 '13 at 18:48