$user_pattern = "/ \@(.+?)([\s|:]|$ )/";  
$str = preg_replace($user_pattern, ' <a href="http://127.0.0.1/${1}">${1}</a> ', $str ); 请问怎么将${1}的中文进行urlencode函数转码?我用下面这样不行,都当成字符串了。$str = preg_replace($user_pattern, ' <a href="http://127.0.0.1/urlencode(${1})">${1}</a> ', $str ); 

解决方案 »

  1.   

    用 preg_replace_callback() 吧,
    如:<?php
    function cb($matches) {
        return sprintf(' <a href="http://127.0.0.1/%1$s">%1$s</a> ',urlencode($matches[1]));
    }
    $user_pattern = "/\@(.+?)([\s|:]|$)/";  
    $str = '[email protected]';
    $str = preg_replace_callback($user_pattern,'cb', $str ); 
    echo $str;
      

  2.   


    好象可以,但两个值都转了,我只要改变一个,就是点击链接里面的,链接显示的文字不改,如只改这个http://127.0.0.1/${1}的正则值,另一个不改。
      

  3.   

    参见preg_replace_callback第5个参数,设为1就只替换一次,而第一次替换便是A标签中的
      

  4.   


    很简单,修改sprintf中的参数即可,
    如:
    function cb($matches) {
        return sprintf(' <a href="http://127.0.0.1/%s">%s</a> ',urlencode($matches[1]),$matches[1]);
    }
      

  5.   

    本帖最后由 xuzuning 于 2013-04-10 09:53:52 编辑
      

  6.   


    从php5.5开始,/e 修饰符开始抛弃,建议使用 preg_replace_callback()
      

  7.   

    我并没有必要糊弄你!$str = ' @中文aa:';
    $user_pattern = "/ \@(.+?)([\s|:]|$ )/e";  
    $str = preg_replace($user_pattern, '" <a href=\"http://127.0.0.1/".urlencode("${1}")."\">${1}</a>"',$str );
    echo $str;<a href="http://127.0.0.1/%D6%D0%CE%C4aa">中文aa</a>
      

  8.   


    好象也不行。
    function cb($matches) {
        return sprintf(' a href="http://127.0.0.1/%1$s">%1$s</a> ',urlencode($matches[1]),$matches[1]);
    }
    $str="测试 @我的微博 添加链接";
    $user_pattern = "/ \@(.+?)([\s|:]|$ )/";
    $str = preg_replace_callback($user_pattern,'cb', $str ); 
    echo $str;
    我故意去掉链接的<符号,看看直接输出效果,还是两个值都会变,输出是:
    测试 a href="http://127.0.0.1/%E6%88%91%E7%9A%84%E5%BE%AE%E5%8D%9A">%E6%88%91%E7%9A%84%E5%BE%AE%E5%8D%9A 添加链接
      

  9.   

    #9 的代码应写作function cb($matches) {
        return sprintf(' a href="http://127.0.0.1/%s">%s</a> ',urlencode($matches[1]),$matches[1]);
    }
    $str="测试 @我的微博 添加链接";
    $user_pattern = "/ \@(.+?)([\s|:]|$ )/";
    $str = preg_replace_callback($user_pattern,'cb', $str ); 
    echo $str;测试 a href="http://127.0.0.1/%CE%D2%B5%C4%CE%A2%B2%A9">我的微博</a> 添加链接
      

  10.   


    哦,谢谢,这个可以,刚才我测试你的代码是没有改正则,就是没有加那个e,所以测的结果是直接输出:
    a href=\"http://127.0.0.1/".urlencode("中文aa")."\">中文aa