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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘