考虑“除”之外的所有正则表达式类型中的转义引号

时间:2019-03-05 22:29:02

标签: php regex

我需要做一些属性内JavaScript替换,以将自定义JavaScript添加到属性。具体而言,在所有代码周围添加一个JS Confirm()函数。相当棘手,但无论如何我都要做。

这是我需要替换的HTML标记。

<input type='submit' id='gform_submit_button_4' class='gform_button button' value='Send'  onclick='/* Lots of JS */' onkeypress='/* Lots of JS */' />

我已成功完成以下PHP代码。

$new_submit_html = $submit_html;
// __() is WordPress's function for internationalized text
$confirm_text = __("It will not be possible to modify your responses anymore if you continue.\\n\\nAre you sure you want to continue?", 'bonestheme');
$new_js_start = 'if( window.confirm("' . $confirm_text . '") ) { ';
$new_js_end = ' } else { event.preventDefault(); }';

$new_submit_html = preg_replace_callback( "/(onclick|onkeypress)(=')([^']*)(')/", function( $matches ) use( $new_js_start, $new_js_end ) {
    $return_val = $matches[1] . $matches[2] . $new_js_start . $matches[3] . $new_js_end . $matches[4];
    // (Other irrelevant manipulations)
    return $return_val;
}, $new_submit_html );

return $new_submit_html;

这现在就像一种魅力,因为我写“很多JS”的JavaScript恰好不包含\'(转义的单引号),它肯定可以包含。

我已经见过this question,它可以使我匹配撇号,除非它被转义了,但是我不确定如何反转它以匹配任何未转义的撇号。我想解决方案将包括回溯,但我不确定在这种情况下如何进行。

1 个答案:

答案 0 :(得分:1)

我将使用DOMDocument来执行此操作,因为只要它们已经有效,它就不会在乎属性的实际内容:

function wrap_js($js) {
    $confirm_text = "It will not be possible to modify your responses anymore if you continue.\\n\\nAre you sure you want to continue?";
    $new_js_start = 'if( window.confirm("' . $confirm_text . '") ) { ';
    $new_js_end = ' } else { event.preventDefault(); }';
    return $new_js_start . $js . $new_js_end;
}
$html = "<input type='submit' id='gform_submit_button_4' class='gform_button button' value='Envoyer'  onclick='/* Lots of JS */' onkeypress='/* Lots of JS */' />";
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
foreach ($xpath->query("//input[@type='submit']") as $submit_input) {
    foreach (['onclick', 'onkeypress'] as $attribute) {
        if (($js = $submit_input->getAttribute($attribute)) != '') {
            $submit_input->setAttribute($attribute, wrap_js($js));
        }
    }
}
echo $doc->saveHTML();

输出:

<input type="submit"
       id="gform_submit_button_4"
       class="gform_button button" 
       value="Envoyer"
       onclick='if( window.confirm("It will not be possible to modify your responses anymore if you continue.\n\nAre you sure you want to continue?") ) { /* Lots of JS */ } else { event.preventDefault(); }'
       onkeypress='if( window.confirm("It will not be possible to modify your responses anymore if you continue.\n\nAre you sure you want to continue?") ) { /* Lots of JS */ } else { event.preventDefault(); }'
>

Demo on 3v4l.org