PHP : 在特定单词周围添加一个 html 标签

PHP : add a html tag around specifc words

我有一个包含文本的数据库,在每个文本中都有以#开头的单词(标签)(记录示例:"Hi I'm posting an #issue on #Whosebug ")

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

所以文本在 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> ...

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

使用 preg_replace(..)

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

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

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

$re = '/\S*#(\[[^\]]+\]|\S+)/m';
$str = 'Some text #tag1 text #tag2 ...';
$subst = '<a href="targetpage.php?val=">#</a>';

$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;

Demo

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

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

试试这个函数

<?php
  $demoString1 = "THIS is #test STRING WITH #abcd";
  $demoString2 = "Hi I'm posting an #issue on #Whosebug";

  function wrapWithAnchor($link,$string){
       $pattern = "/#([a-zA-Z0-9]+)/";
       $replace_with = '<a href="'.$link.'?val="><a>';

       return preg_replace( $pattern, $replace_with ,$string ); 
 }

   $link= 'http://www.targetpage.php';
   echo wrapWithAnchor($link,$demoString1);
   echo '<hr />';
   echo wrapWithAnchor($link,$demoString2);

 ?>