简体   繁体   English

Php正则表达式将href =“URL”替换为onclick = myfunction(URL)

[英]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: 使用Php,我想将所有链接替换为JavasSript函数,例如:

From: <a href="URL">abc</a> 来自: <a href="URL">abc</a>

to <a onclick="SomeFunction(URL);">abc</a> <a onclick="SomeFunction(URL);">abc</a>

You should use DOM operations like those provided by PHP's DOM : 你应该使用像PHP的DOM提供的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... 在没有正则表达式的情况下解析HTML有一些东西可以说...

$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 如果你想保持href只是使用

$elem->setAttribute('href', "")

or whatever the proper syntax is, I didn't test that. 或者无论正确的语法是什么,我都没有测试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM