简体   繁体   English

PHP:在特定单词周围添加html标记

[英]PHP : add a html tag around specifc words

I have a data base with texts and in each text there are words (tags) that start with # (example of a record : "Hi I'm posting an #issue on #Stackoverflow ") 我有一个包含文本的数据库,并且每个文本中都有以#开头的单词(标签)(记录示例:“嗨,我正在#Stackoverflow上发布#issue”)

I'm trying to find a solution to add html code to transform each tag into a link when printing the text. 我正在尝试找到一种解决方案,以添加html代码以在打印文本时将每个标签转换为链接。

So the text are stored as strings in MySQL database like this : 因此,文本以字符串形式存储在MySQL数据库中,如下所示:

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

I want to replace all these #abcd with 我想将所有这些#abcd替换为

<a href="targetpage.php?val=abcd">#abcd</a>

And have a final result as follow: 并得出以下最终结果:

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

I guess that i should use some regex but it is not at all my strong side. 我想我应该使用一些正则表达式,但这并不是我的强项。

Try the following using preg_replace(..) 使用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 http://php.net/manual/en/function.preg-replace.php

A simple solution could look like this: 一个简单的解决方案如下所示:

$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 演示

If you are actually after Twitter hashtags and want to go crazy take a look here how it is done in Java. 如果您实际上是在使用Twitter主题标签并且想发疯,请在这里看看如何用Java完成。

There is also a JavaScript Twitter library that makes things very easy. 还有一个JavaScript Twitter库 ,使事情变得非常容易。

Try this the function 试试这个功能

<?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);

 ?>

在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM