首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找hashtag

查找hashtag
EN

Stack Overflow用户
提问于 2013-01-09 22:21:30
回答 2查看 411关注 0票数 2

我有一个包含文本的字符串,在一些地方会有一个twitter风格的标签。我想找到它们并创建一个单独的变量,其中所有这些变量都由空格分隔。我还想将原始字符串中的所有标签转换为链接。示例:

代码语言:javascript
复制
$string = "Hello. This is a #hashtag and this is yet another #hashtag. This is #another #example."

after函数:

代码语言:javascript
复制
$string_f = "Hello this is a <a href='#'>#hashtag</a> and this is yet another <a href='#'>#hashtag</a>. This is <a href='#'>another</a> <a href='#'>example</a>";

$tags = '#hashtag #another #example';
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-09 22:26:46

要查找所有散列标记,请使用正则表达式和preg_match_all(),并使用preg_replace()进行替换

代码语言:javascript
复制
$regex = '/(#[A-Za-z-]+)/';
preg_match_all( $regex, $string, $matches);
$string_f = preg_replace( $regex, "<a href='#'>$1</a>", $string);

然后所有标签都在$matches[1]中的一个数组中

代码语言:javascript
复制
$tags_array = $matches[1];

然后,使用implode()array_unique()将其转换为空格分隔的列表

代码语言:javascript
复制
$tags = implode( ' ', array_unique( $tags_array));

你就完事了。您可以从this demo中看到$tags$string_f是:

代码语言:javascript
复制
"#hashtag #another #example"
"Hello. This is a <a href='#'>#hashtag</a> and this is yet another <a href='#'>#hashtag</a>. This is <a href='#'>#another</a> <a href='#'>#example</a>."

对于哈希标记中的其他字符(例如数字),请相应地修改$regex

编辑:但是,如果您使用preg_replace_callback()和闭包,则可以提高效率,这样您只需执行一次正则表达式,如下所示:

代码语言:javascript
复制
$tags_array = array();
$string_f = preg_replace_callback( '/(#[A-Za-z-]+)/', function( $match) use( &$tags_array) { 
    $tags_array[] = $match[1];
    return "<a href='#'>" . $match[1] . "</a>";
}, $string);
$tags = implode( ' ', array_unique( $tags_array));
票数 6
EN

Stack Overflow用户

发布于 2013-01-09 22:26:26

来个漂亮的正则表达式怎么样?

代码语言:javascript
复制
preg_match_all("/#[\w\d]+/", $string, $matches, PREG_SET_ORDER);
unset($matches[0]);
$tags = implode(" ", $matches);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14237317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档