在 php 的字符串中查找主题标签


Find a hashtag in a string in php

我想在我的字符串周围添加一个链接,即

    "My new Tweet **#new** this is cool".

我想让主题标签 #new 包装到一个链接中。

之后,我会得到:

    "My new Tweet <a href="http://twitter.com/search/%23new">new</a> this is cool.

我该怎么做?

试试这个:

$string = "My new Tweet **#new** this is cool".
$linked_string = preg_replace('/'*'*('#(.*?))'*'*/', '<a href="http://twitter.com/search/$1">$2</a>', $string);

假设您的 hastag 只包含字母和数字,您可以使用以下代码:

$string = preg_replace('/'*'*#([a-zA-Z0-9]+)'*'*/', '<a href="http://twitter.com/search/%23$1">$1</a>', $string);

您可以根据需要轻松更改正则表达式的内容。

这可能会做到:

$yourString = 'My new Tweet **#new** this is cool';
$yourString = preg_replace_callback('/'*'*(#(.+?))'*'*/', function($matches) {
    $html = '<a href="http://twitter.com/search/%s">%s</a>';
    return sprintf($html, urlencode($matches[1]), htmlentities($matches[2]));
}, $yourString);