比如一个页面的源代码里有<body onload="abc();">....</body>
我想在abc();前插入一个init(); 请问如何做到.
原始的字符串里可能没有onload="",body 和 onload里也可能有其它字符串.
总之要考虑很多其它因素,万无一失.
多谢了

解决方案 »

  1.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script>
    function abc(){ // 原来abc方法
    alert('abc');
    } function init(){
    alert('init');
    } var tmp = abc;
    abc = function(){ // 重置 abc方法
    init();
    tmp();
    }; 

    </script>
    </head><body onload='abc()'>
    </body>
    </html>
      

  2.   

    <?php
    $str='<body onload="abc();">.... ';
    $reg = '/(<body.+?)onload="(.+?>)/i';
    $str = preg_replace($reg, '$1onload="init();$2', $str);
    echo $str;
    ?>
      

  3.   


    <?php
        $str='<body onload="abc();">.... ';
        $str = preg_replace('/(<body[^>]+)onload=[\"\']([^>]+)[\"\']/i', '$1onload="init();$2"', $str);
        echo $str;
    ?>