Click to See Complete Forum and Search --> : how to extract the onclick value from a string


jasongr
01-25-2005, 11:11 AM
Hello

Assuming a string has the value:
onclick="<javascript code here>"
or
onclick='<javascript code here>'

is there an easy method using regular expression to obtain the JavaScript code without resorting to parsing?
onclick is case insensitive and the <javascript code here> may contain double or single quotes, but you can assume it is legal

any help would be appreciated

NogDog
01-25-2005, 11:54 AM
This seems to work:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>
<title>Untitled</title>
<style type="text/css">
</style>
</head>
<body>

<?php
$test = <<<EOD
<submit value='submit' onClick="this.is.a.('test');it.is.only.a('test');">
EOD;

echo "<p>Initial string: <strong>". htmlentities($test) . "</strong></p>\n";
preg_match("/onclick=[\"\\\\'](.*;)[\"\\\\']/i", $test, $matches);
echo "<p>Result of preg_match: <strong>{$matches[1]}</strong></p>\n";
?>

</body>
</html>

jasongr
01-25-2005, 02:04 PM
thanks a lot
this works very well

do you know of a good book for learning regular expressions?
or maybe a good site?

Jona
01-25-2005, 02:22 PM
Try http://www.regularexpressions.info/.

jasongr
01-25-2005, 02:35 PM
Thanks a lot
I will give it a try

pyro
01-25-2005, 02:43 PM
Mastering Regular Expressions (http://www.amazon.com/exec/obidos/tg/detail/-/0596002890/qid=1106685741/sr=8-1/ref=pd_csp_1/002-9363315-6216031?v=glance&s=books&n=507846) by Jeffrey Friedl.