Search code examples
phpstringechohref

Match link text and querystring of href PHP


I am using PHP.

I need to take the text inside the a tag and add it to the querystring of the href attribute.

Example:

<a href="page.php">sometext</a> 

becomes:

<a href="page.php?q=sometext">sometext</a> 

So I just links any word to page.php, but when a user clicks on it it goes "page.php?q=sometext", or the actual link changes from "page.php" to "page.php?q=sometext".

If possible, please make an example using jsfiddle.net or phpfiddle.org


Solution

  • You can do this in the client side with jQuery:

    <script type="text/javascript">
        $(function(){
            $('a').each(function(index, element){
                href = $(element).attr('href');
                $(element).attr('href', href + "?q=" + $(element).text());
            });
        });
    </script>
    

    an example: https://jsfiddle.net/jgj7k19o/