开发者

Some nifty regex to parse some javascript inside HTML

开发者 https://www.devze.com 2023-01-07 06:16 出处:网络
I have some HTML that looks like this: $(document).ready(function(){ $(\'#cum开发者_C百科ulative-returns\').graph({

I have some HTML that looks like this:

    $(document).ready(function(){
        $('#cum开发者_C百科ulative-returns').graph({
            width: 400,
            height: 180,
            type: 'bar',
            x_label: 'Month',
            x_data: ['Jan','Feb','Mar','Apr'],
            y_label: 'Cumulative Return',
            y_data: ['5','10','15','20'],
            colors: ['666666', '000000', 'ff0000', '333366']
        });

        $('#new-returns').graph({
            width: 400,
            height: 180,
            type: 'bar',
            x_label: 'Month',
            x_data: ['Jan','Feb','Mar','Apr'],
            y_label: 'Cumulative Return',
            y_data: ['5','10','15','20'],
            colors: ['666666', '000000', 'ff0000', '333366']
        });
    });

What I need to do is replace x_data and y_data with new values using some nifty regex in PHP.

This is what I have come up with so far just to find the right graph but even that doesn't work.

$graph = "cumulative-returns";
$start_tag = '$(\'#'.$graph.'\').graph({';
$end_tag = '});';
preg_match_all("/".preg_quote($start_tag)."(.+?)".preg_quote($end_tag)."/i", $html, $matches);
print_r($matches);

Any suggestions would be great!

*edit:

Please ignore the fact that its javascript, I just need to some regex to find the string between $('#cumulative-returns').graph({ and }); characters!


preg_match('/\$\(\'#cumulative-returns\'\)\.graph\({([^}]*)}\);/s',$input,$matches);

After this, $matches[0] will have the values matched by the regex (including the surrounding text) and $matches[1] will have just the text between $('#cumulative-returns').graph({ and }); characters.

Also, possibly more useful, would be:

preg_match_all('/\$\(\'#[^\']*\'\)\.graph\({([^}]*)}\);/s',$input,$matches);

After which matches[0][n] reflects the nth match (including surrounding text) and $matches[1][n] reflects the nth instance of text between $('#[any-text]').graph({ and });


create a variable to hold the x_data data Then just manipulate that variable ...

var myvar = ['dec', 'may', 'whatever', 'whatver' ]
    $('#cumulative-returns').graph({
                width: 400,
                height: 180,
                type: 'bar',
                x_label: 'Month',
                x_data: myvar,
                y_label: 'Cumulative Return',
                y_data: ['5','10','15','20'],
                colors: ['666666', '000000', 'ff0000', '333366']
            });
0

精彩评论

暂无评论...
验证码 换一张
取 消