PHP:用querystring替换匹配的文本

时间:2017-10-04 06:57:28

标签: php jquery match href

我有一些缩写词,如诗句:

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

我目前正在jquery转换这些链接:

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

并按如下方式进行:

<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>

用于此的脚本是:

$(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
  });
});

我需要的是将> <之间的文本翻译成适当的数字(Mt = 80,Lu = 81,Rv = 92,Nd = 95 ......等),因此转换的链接变为:

<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>

1 个答案:

答案 0 :(得分:1)

您需要使用预定义的值创建一个jQuery数组,并且必须使用链接文本的第一个值作为数组索引来获取相应的值。

检查以下代码段: -

&#13;
&#13;
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
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

注意: -

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