不会写正则真痛苦。。
我想实现,
如果输入的是
 转为<span class="style4" ><a href="show.php?id=5">点击</a></span>/**************************************************/里面的id:5  中的5是变量,style:4中的4也是变量.请问这个正则如何实现?

解决方案 »

  1.   

    <?php
    // \\2 是一个逆向引用的例子,其在 PCRE 中的含义是
    // 必须匹配正则表达式本身中第二组括号内的内容,本例中
    // 就是 ([\w]+)。因为字符串在双引号中,所以需要
    // 多加一个反斜线。
    $html = "<b>bold text</b><a href=howdy.html>click me</a>";preg_match_all ("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches);for ($i=0; $i< count($matches[0]); $i++) {
      echo "matched: ".$matches[0][$i]."\n";
      echo "part 1: ".$matches[1][$i]."\n";
      echo "part 2: ".$matches[3][$i]."\n";
      echo "part 3: ".$matches[4][$i]."\n\n";
    }
    ?>  本例将输出: matched: <b>bold text</b>
    part 1: <b>
    part 2: bold text
    part 3: </b>matched: <a href=howdy.html>click me</a>
    part 1: <a href=howdy.html>
    part 2: click me
    part 3: </a>
     
      

  2.   

    $str = "";
    preg_match("/\[img\](([a-z]+):([0-9]),)*([a-z]+):([0-9])\[\/img\]/i", $str, $matches);
    print_r($matches);
    for($i=2; $i<count($matches); $i+=2) {
    $att[$matches[$i]]=$matches[$i+1];
    }
    echo "<span class=\"style{$att['style']}\" ><a href=\"show.php?id={$att['id']}\">点击 </a> </span>";
      

  3.   

    $str = "请点击这里。这是第二个链接";
    请问这样如何实现???
      

  4.   

    function replaceit($att_str)
    {
    $att_arr=explode(',', $att_str);
    foreach($att_arr AS $att_line) {
    list($attname,$attvalue)=explode(':',$att_line);
    $atts[$attname]=$attvalue;
    }
    return "<span class=\"style{$atts['style']}\" ><a href=\"show.php?id={$atts['id']}\">点击 </a> </span>";
    }
    $str = "other contentother contentother content";
    echo preg_replace("/\[img\](([a-z]+:[0-9],?)+)\[\/img\]/ie", "replaceit('\\1')", $str)
    那这个更有通用性。
      

  5.   

    把replaceit里的return字符串换成任何你想代替的就可以了。
      

  6.   

    直接给答案, 请不要说我教怪你
    $string = 'i want to make a test ! ,go';
    $pattern = '/\[img\]id:(\d+),style:(\d+)\[\/img\]/is';
    $replacement ='<span class="style$1" ><a href="show.php?id=$2">点击</a></span>';
    echo preg_replace($pattern, $replacement, $string);