I have a sample code:
$link = '<a href="http://test.com/t123#readmore" class="">Read more</a>';
And my code php add onlick event
$link = preg_replace( '#<a(.+?)href="(.+?)"(.+?)(</a>)#s', '<a href="$2" onclick="test();"></a>', $link);
But error can't add onclick on tag a, how to fix it ?
<a href="http://test.com/t123#readmore" onclick="test();" class="">Read more</a>
Looks pretty good to me... you're missing Read More
though... add your third match into your preg_replace
statement:
$link = preg_replace( '#<a(.+?)href="(.+?)"(.+?)(</a>)#s', '<a href="$2" onclick="test();">$3</a>', $link);
// <a href="http://test.com/t123#readmore" onclick="test();"> class="">Read more</a>
Demo: https://eval.in/66235
I don't recommend using a regex to do this. If you're going to do this, do it with Javascript and jQuery instead
<script>
$(document).ready(function() {
$('#testa').click(function() { test(); });
});
</script>
<a href="http://test.com/t123#readmore" onclick="test();" class="" id="testa">Read more</a>