Search code examples
phpmysqlmysqlistr-replacepreg-replace-callback

str_replace inside a preg_replace_callback not working.


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.


Solution

  • 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;