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

时间:2016-03-11 08:51:39

标签: php regex string obfuscation preg-match-all

我试图匹配以下类名。

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

但只有&#34;文章&#34; className匹配。

我尝试过以下方法。

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

1 个答案:

答案 0 :(得分:1)

你的错误在这里:

    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:看看我在最后一行的评论