【问题标题】:PHP : add a html tag around specifc wordsPHP:在特定单词周围添加一个 html 标签
【发布时间】:2018-06-01 14:39:20
【问题描述】:

我有一个包含文本的数据库,并且在每个文本中都有以 # 开头的单词(标签)(记录示例:“嗨,我正在 #Stackoverflow 上发布 #issue”)

我正在尝试找到一种解决方案,在打印文本时添加 html 代码以将每个标签转换为链接。

所以文本以字符串形式存储在 MySQL 数据库中,如下所示:

一些文字#tag1 文字#tag2 ...

我想用

替换所有这些#abcd
<a href="targetpage.php?val=abcd">#abcd</a>

最终结果如下:

Some text <a href="targetpage.php?val=tag1">#tag1</a> text <a href="targetpage.php?val=tag2">#tag2</a> ...

我想我应该使用一些正则表达式,但这根本不是我的强项。

【问题讨论】:

    标签: php html css regex preg-replace


    【解决方案1】:

    使用preg_replace(..)尝试以下操作

    $input = "Hi I'm posting an #issue on #Stackoverflow";
    echo preg_replace("/#([a-zA-Z0-9]+)/", "<a href='targetpage.php?val=$1'>#$1</a>", $input);
    

    http://php.net/manual/en/function.preg-replace.php

    【讨论】:

    • 在锚标记结束前添加 # 和 $1 变量以匹配请求的输出。
    【解决方案2】:

    一个简单的解决方案可能如下所示:

    $re = '/\S*#(\[[^\]]+\]|\S+)/m';
    $str = 'Some text #tag1 text #tag2 ...';
    $subst = '<a href="targetpage.php?val=$1">#$1</a>';
    
    $result = preg_replace($re, $subst, $str);
    echo "The result of the substitution is ".$result;
    

    Demo

    如果您真的在关注 Twitter 主题标签并想发疯,请查看 here 它是如何在 Java 中完成的。

    还有一个JavaScript Twitter library 让事情变得非常简单。

    【讨论】:

    • 如果您想超越这一点,请查看此answer。
    • 非常感谢。看起来不错!我会尝试并与您保持联系!
    【解决方案3】:

    试试这个功能

    <?php
      $demoString1 = "THIS is #test STRING WITH #abcd";
      $demoString2 = "Hi I'm posting an #issue on #Stackoverflow";
    
      function wrapWithAnchor($link,$string){
           $pattern = "/#([a-zA-Z0-9]+)/";
           $replace_with = '<a href="'.$link.'?val=$1">$1<a>';
    
           return preg_replace( $pattern, $replace_with ,$string ); 
     }
    
       $link= 'http://www.targetpage.php';
       echo wrapWithAnchor($link,$demoString1);
       echo '<hr />';
       echo wrapWithAnchor($link,$demoString2);
    
     ?>
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多