简体   繁体   中英

PHP Preg Match All fails when matching string with HTML.

I'm trying to match the class names in the following.

<section className="content_main_container">
<article className="comment_user_propic">

But only the "article" className is matched.

I've tried the following.

function comments(){
    $str = <<<EOT

    '<section className="content_main_container">
    <article className="comment_user_propic">'

EOT;

return $str;
}

class obfusicate {  

    function change($str, $prefix){

        preg_match_all('#'.$prefix.'="(.*?)"#',$str,$parts);

        $array_len          = count($parts[1]);
        $class_count        = 0;
        $c_array            = [];

        foreach($parts[1] as $part){
            $rand_name      = self::rand_g();
            $c_array[$part] = $rand_name;   

            ++$class_count;     
            $str_1      = str_replace($part, $rand_name, $str);
        }

        return ['array'=>$c_array, 'string'=>$str_1];
    }
}

$obs        = new obfusicate;
$result     = $obs->change(comments(), 'className');

echo var_dump($result['string']);

Your bug is here:

    foreach($parts[1] as $part){
        $rand_name      = self::rand_g();
        $c_array[$part] = $rand_name;   

        ++$class_count;     
        $str_1      = str_replace($part, $rand_name, $str); //each time you start over replacing from $str and you lose your last $str_1 value
    }

    return ['array'=>$c_array, 'string'=>$str_1]; //Assigned after the loop so only the last $str_1 value is stored

EDiT: Look at my comment in the last line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM