Search code examples
phpjquerymatchhref

PHP: Replace Matched text with querystring


I have a list of abbreviations like verses:

Mt=80
Lu=81
Rv=92
Nd=95
etc.

And I am currently jquery to convert these links:

<a href="page.php?q=Mt 5: 2">Mt 5: 2</a>
<a href="page.php?q=Mt 5: 2">Nd 14: 25</a>

and makes them as follows:

<a href="page.php?book=Mt&chapter=5&vmin=2">Mt 5: 2</a>
<a href="page.php?book=Nd&chapter=15&vmin=25">Nd 14: 25</a>

The script being used to that is:

$(document).ready(function() {
  $("a[href='page.php']").each(function(index, element){
    href = $(element).attr('href'); // get the href
    text = $(element).text().split(' '); // get the text and split it with space
    $(element).attr('href', href + "?book=" +$.trim(text[0])+"&chapter="+$.trim(text[1].slice(0,-1))+"&vmin="+$.trim(text[2])); //create desired href and replace it with older-one
  });
});

What I need is to translate the text between > < to the appropriate number (Mt=80, Lu=81, Rv=92, Nd=95.. etc.), so the converted links becomes like:

<a href="page.php?book=80&chapter=5&vmin=2">Mt 5: 2</a>
<a href="page.php?book=95&chapter=15&vmin=25">Nd 14: 25</a>

Solution

  • You need to create a jQuery array with your pre-defined values and you have to use first value of link text as an array index to get corresponding value.

    Check the below snippet:-

    var myarray = {'Mt':80, 'Lu':81, 'Rv':92, 'Nd':95};// you can add more values
    $(document).ready(function() {
      $("a[href='page.php']").each(function(index, element){
        href = $(element).attr('href'); // get the href
        text = $(element).text().split(' '); // get the text and split it with space
        $(element).attr('href', href + "?book=" +$.trim(myarray[text[0]])+"&chapter="+$.trim(text[1].slice(0,-1))+"&vmin="+$.trim(text[2])); //create desired href and replace it with older-one
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="page.php">Mt 5: 2</a><br>
    <a href="page.php">Nd 14: 25</a>

    Note:-

    myarray[text[0]] == myarray['Mt'] ==80; //.... so on for other values as well