在Div中查找关键字,然后获取冒号后的字符串,并将其转换为变量


Find a keyword in a Div, then get the string after colon, and turn it to a variable

试图找出如何在jquery, javascript或php中做到这一点…我有一个div或p标签,里面有文本。
例如:

<p>John likes math.  John sid: CA1001 Susie likes English: Susie sid: CA1002</p>

我要做的是首先找到段落或div标签内的所有sid:(s)。每找到一个,我想在冒号前得到id字符串id将有6个字符。然后,将id字符串转换为一个变量,这样我就可以用一个链接来替换id号。
为例:

<a href='http://www.website.com/studentinformation?id=$studentid'>CA1001</a>

差不多就是这样。这样每次在div中出现id时,我的代码就会将id转换为链接。这可能吗?

您可以使用正则表达式

在你的例子中,你说所有的边都是以下格式

sid:
space
6 digits or chacters

正则表达式是这样的/sid: (.{6})/g

之后,您需要将p或div或其他元素中的文本替换为regex可以找到的链接和ID。

var pattern = /sid: (.{6})/g; // pattern to match sid: 000000
$('p').each(function(i,e) {
    // find matches and replace
    $(e).html($(e).html().replace(pattern, '<a href="http://www.website.com/studentinformation?id=$1">$1</a>'));
});

小提琴工作演示-这不是优化,只是简单的代码。

如果您想在服务器端处理它,我将抛出一个PHP解决方案。

<?php 
// This can be all of your text after you compile it or you could loop
$in = "<p>John likes math.  John sid: CA1001 Susie likes English: Susie sid: CA1002</p>";
// Set up what we're finding and what we will replace it with
$pattern = '/sid: (.{6})/'; 
$replace = 'sid: <a href="http://www.website.com/studentinformation?id=$1">$1</a>'; 
// Filter the text with our parameters
$out = preg_filter( $pattern, $replace, $in ); 
// Dump to the browser
echo $out;

真棒…谢谢你!试图让我的记忆再次编码…我将尝试javascript和服务器端…

现在如果我想把它放在页面上的一个div…我可能需要用这个div标签创建一个id,比如:

 <div id="test">This is my text that has sid: CA0056<br /> This is my text that is second has another sid: CA0055</div> 

然后我想在javascript中做的是。

 var src_str = $("#test");
 var theHtml = src_str.html();

是正确的javascript????如何在php上一个特定的div ?

您需要:

  1. 获取你需要更新的所有段落
  2. 提取段落内容
  3. 查找所有子字符串来替换
  4. 提取id,构建链接html并将3中的子字符串替换为这些链接

检查demo - https://fiddle.jshell.net/ermakovnikolay/uu9ka8gt/和下面的代码:

function replacer(match) {
   var m = match.split(' ')[1];
   return '<a href="http://www.website.com/studentinformation?id=' + m + '">' + m + '</a>';
}
$('p').each( function(index, paraElement) {
   paraElement.innerHTML = paraElement.innerHTML.replace(/sid:.{7}/gi, replacer );
});