I need to do some in-attribute JavaScript replacement to add custom JavaScript to the attribute. To be specific, to add a JS confirm() function around all of it. A rather hacky thing, but a thing I have to do regardless.
Here is the HTML tag I need to replace.
<input type='submit' id='gform_submit_button_4' class='gform_button button' value='Send' onclick='/* Lots of JS */' onkeypress='/* Lots of JS */' />
I have succeeded in doing it with the following PHP code.
$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;
This works like a charm right now, because the JavaScript where I wrote "Lots of JS" just so happens not to contain \'
-- escaped single quotes -- which it could definitely contain.
I've seen this question, which would allow me to match the apostrophe unless it's escaped, but I'm not sure how to reverse it to match anything but an unescaped apostrophe. I imagine the solution will include lookbehinds, but I'm not sure how to proceed in this exact case.