doufu8127 2014-03-07 02:17 采纳率: 100%
浏览 256
已采纳

查找并替换以某些字符开头的文本中的所有字符串

I am attempting to allow users to link to other wallposts within their own wallposts. so for example if user types: Please see post ::35 for more information I would change the string to: Please see <a href="posts/35">35</a> for more information

I have the following function which grabs all the post numbers from the content, as denoted by :: at the beginning.

function getBetween($content, $start, $end, $rest = array()) {
    $r = explode($start, $content, 2);
    if (isset($r[1])) {
        $r = explode($end, $r[1], 2);
        $rest[] = $r[0];
        return getBetween($r[1], $start, $end, $rest);
    } else {
        return $rest;
    }
}

$post = 'Lorem ::35 ipsum ::36 dolor sit ::37 ::38';
$links = getBetween($post, '##', ' ');

$links returns an array containing 35, 36, 37, 38. What I don't know is how I can replace them in the original string with the hyperlinks.

  • 写回答

2条回答 默认 最新

  • duankui6150 2014-03-07 02:33
    关注

    This code will find ::digit that is flanked by white space or appears at the start or end of the text.

    $post = 'Lorem ::35 ipsum ::36 dolor sit ::37 ::38';
    $post = preg_replace('/(\G|\s+|^)::(\d+)((?=\s+)|(?=::)|$)/','$1 <a href="?postid=$2">$2</a> $3',$post);
    echo $post;
    
    // Lorem <a href="?postid=35">35</a> ipsum <a href="?postid=36">36</a> dolor sit <a href="?postid=37">37</a> <a href="?postid=38">38</a>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度