PHP 将字符串与 HTML 匹配时,Preg Match All 失败。

PHP Preg Match All fails when matching string with HTML.

我正在尝试匹配以下 class 名称。

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

但只有 "article" class名称匹配。

我尝试了以下方法。

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']);

你的错误在这里:

    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

编辑:看我最后一行的评论