Php Regular Expression to Replace href=“URL” to onclick=myfunction(URL)
With Php, I want to replace all links to a JavasSript function, for example:
From:
<a href="URL">abc</a>
to
<a onclick="SomeFunction(U开发者_如何学运维RL);">abc</a>
You should use DOM operations like those provided by PHP’s DOM:
$doc = new DOMDocument();
$doc->loadHTML($html);
foreach ($doc->getElementsByTagName('a') as $elem) {
if ($elem->hasAttribute('href')) {
$elem->setAttribute('onclick', 'SomeFunction('.json_encode($elem->getAttribute('href')).')');
$elem->removeAttribute('href');
}
}
<script>
function SomeFunction(url) {
window.location.href = url;
}
</script>
<?php
$html = '<a href="http://www.google.com">Google</a>';
$html = preg_replace('/<a href="(.+?)">/', '<a href="javascript:void(0);" onclick="SomeFunction(\'$1\');">', $html);
echo $html;
?>
There is something to be said about parsing HTML without regex...
$str = 'Hello <a href="bob">bob</a>
<p><a href="hello">heya</a>';
$dom = new DOMDocument();
$dom->loadHTML($str);
foreach($dom->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
$a->removeAttribute('href');
$a->setAttribute('onclick', 'SomeFunction(\'' . $href . '\')');
}
echo $dom->saveHTML();
Output
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>Hello <a onclick="SomeFunction('bob')">bob</a>
</p>
<p><a onclick="SomeFunction('hello')">heya</a></p>
</body></html>
if you want to keep the href
just use
$elem->setAttribute('href', "")
or whatever the proper syntax is, I didn't test that.
精彩评论