dongniaocheng3773 2018-08-20 09:04
浏览 34
已采纳

如何用带有小写标签的链接替换标签搜索结果?

There is a text, for example:

> This is a Car

And a dynamic list of tags. For example:

c, car

Expected result is to get this after processing:

This is a <a href='car.ly?search=car'>Car</a>

So:

  1. It should replace tags with links to search results to these tags
  2. Longer tags should have prority over shorter tags
  3. It should not replace tags inside "to phrase", for example "c" in "car.ly" etc.
  4. search term should be lower case, and title letter case of the tag the same as the original
  5. It should ommit tags and styling features in input text (it can contain HTML)

I have tested several solutions and no success with it. What is the proper way to handle this case? How to replace tags with a links to search results properly?

  • 写回答

1条回答 默认 最新

  • dthtvk3666 2018-08-20 09:56
    关注

    As far as I understand your question, I think you may want to use preg_replace_callback():

    // A test string & some tags
    $str = 'This is a Car c ar';
    $tags = [ 'c', 'AR', 'car' ];
    
    // sort tags by length
    usort($tags, function ($a, $b) { return strlen($b)-strlen($a); });
    
    // Then, replace tags one per one
    foreach ($tags as $t) {
    
        // Will replace tag between whitespaces or start/end of string
        $str = preg_replace_callback('/(?<=\s|^)' . $t . '(?=\s|$)/i', function ($matches) {
            return '<a href="' . strtolower($matches[0]) . '.ly?search=' . strtolower($matches[0]) . '">' . $matches[0] . '</a>';
        }, $str);
    }
    

    Output:

    <!-- echo $str; -->
    This is a <a href="car.ly?search=car">Car</a> <a href="c.ly?search=c">c</a> <a href="ar.ly?search=ar">ar</a>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制