【问题标题】:Locate hashtags找到主题标签
【发布时间】:2012-12-23 14:58:45
【问题描述】:

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

$string = "Hello. This is a #hashtag and this is yet another #hashtag. This is #another #example."

函数后:

$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';

【问题讨论】:

标签: php


【解决方案1】:

要查找所有哈希标签,请使用正则表达式和preg_match_all(),然后用preg_replace() 替换:

$regex = '/(#[A-Za-z-]+)/';
preg_match_all( $regex, $string, $matches);
$string_f = preg_replace( $regex, "<a href='#'>$1</a>", $string);

那么所有的标签都在$matches[1]的一个数组中:

$tags_array = $matches[1];

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

$tags = implode( ' ', array_unique( $tags_array));

你就完成了。从this demo可以看出$tags$string_f分别是:

"#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() 和闭包,则可以提高效率,因此您只需执行一次正则表达式,如下所示:

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

【讨论】:

    【解决方案2】:

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

    preg_match_all("/#[\w\d]+/", $string, $matches, PREG_SET_ORDER);
    unset($matches[0]);
    $tags = implode(" ", $matches);
    

    【讨论】:

      猜你喜欢
      • 2012-11-26
      • 2019-11-03
      • 2017-11-15
      • 1970-01-01
      • 2018-06-26
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多