如何从锚标记的href属性中提取参数“sid”的值

时间:2012-12-10 20:16:35

标签: javascript html regex

我有div块,里面有锚标签。

如何从每个锚标记的href属性中提取属性“sid”的值?

我获取代码数据的方式:

$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com&callback=?', function(data){
        //$('#output').html(data.contents);


 var code = data.contents;

 document.myform.outputtext.value = code

我试过这个,但它没有输出href的值?

var pattern = /<a href="([^"]+?)">/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write(code[i].replace(pattern, '<a href="./doit.php?Id=$1&title=$2">$2</a><br />'));
}

代码字符串示例:

<td width=120 valign="top">                     <div style="height:135px;
    border:1px solid #BBBBBB; background:#BBBBBB; margin-left:2px;
    text-align:center; ">
                    <a href="/now/episodes.php?name=path&id=4000&sid=12345&page=0"><img
    border="0" src="http://www.somesite.com/1234.jpg" width="150"
    height="83"></a><br>
                        <font face="Tahoma" size="2"><b>Star Album</b><br/>
                            episode 4
                        </font>             </div>


        </td>

2 个答案:

答案 0 :(得分:1)

尝试:

var url="/now/episodes.php?name=path&id=4000&sid=12345&page=0"

var match = url.match(/sid=(.*)\&/);
alert( match[1] );​

答案 1 :(得分:0)

<?php
$referenceStr = "<td width=120 valign=\"top\">                     <div style=\"height:135px;
    border:1px solid #BBBBBB; background:#BBBBBB; margin-left:2px;
    text-align:center; \">
                    <a href=\"/now/episodes.php?name=path&id=4000&sid=12345&page=0\"><img
    border=\"0\" src=\"http://www.somesite.com/1234.jpg\" width=\"150\"
    height=\"83\"></a><br>
                        <font face=\"Tahoma\" size=\"2\"><b>Star Album</b><br/>
                            episode 4
                        </font>             </div>


        </td>";

$key = 'sid';   
preg_match('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', $referenceStr,$matches);
foreach($matches as $k => $v) $matches[$k] = str_replace(array('&sid=','sid='),'',$v);
print_r($matches);
?>

这是一个PHP解决方案,只需使用该模式,它也适用于JS。

对于JS:

var code = '<td width=120 valign="top"> <div style="height:135px; border:1px solid #BBBBBB; background:#BBBBBB; margin-left:2px; text-align:center; "> <a href="/now/episodes.php?name=path&id=4000&sid=12345&page=0"><img border="0" src="http://www.somesite.com/1234.jpg" width="150" height="83"></a><br> <font face="Tahoma" size="2"><b>Star Album</b><br/> episode 4 </font> </div> </td>';
matchingelements = code.match(/sid\=*(\d*)/ig);
for(i=0;i<code.length;i++){
    document.write(matchingelements[i].replace('&sid=','').replace('sid=',''));
}

输出12345