【问题标题】:PHP: Match text respectively with querystringPHP:将文本分别与查询字符串匹配
【发布时间】:2018-03-15 10:56:31
【问题描述】:

我有以下行:

<a href="page.php">Mt 5: 2</a>

我使用 jquery 代码来回显(匹配)&gt; &lt; 括号之间的任何内容,并使链接如下:

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

现在我需要链接如下:

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

我目前用来匹配所有的代码是:

$(document).ready(function() {
$("a[href='page.php']").each(function(index, element){
   href = $(element).attr('href');
   $(element).attr('href', href + "?q=" + $(element).text());
});
});

所以我需要将&gt; &lt; 之间的任何内容分别分为三个部分:

  1. 将 Mt 添加到 ?book= → ?book=Mt
  2. 将 5 添加到 &chapter= → &chapter=5
  3. 将 2 添加到 &vmin= → &vmin=2

【问题讨论】:

  • 这种文本格式 (Mt 5: 2) 对于所有 &lt;a&gt; 都是固定的?
  • 感谢您的回复。不,它会改变,就像诗句一样。例如:Mt 5: 2 - Mt 7: 4 - Mk 12: 27 - Rv 15: 12
  • 当前代码匹配 > Mt 5: 2 - 我需要编辑代码以制作这样的链接:Mt 5: 2
  • 是的,这就是我要问的,格式保持不变,但值发生了变化。

标签: php jquery match echo href


【解决方案1】:

您需要拆分每个链接的文本并分别使用所有三个值来制作您想要的href,如下所示:-

$(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
  });
});
<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">Mt 7: 2</a><br>
<a href="page.php">Mt 10: 2</a><br>

注意:-

trim() 用于删除多余的空格,如果值有任何(前导/尾随空格)。

slice() 用于从第二个值中删除 :

【讨论】:

猜你喜欢
  • 2018-03-15
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2011-01-16
相关资源
最近更新 更多