1

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

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

我想将#new 标签包含在一个链接中。

之后,我会得到:

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

我怎么能那样做?

4

3 回答 3

2

试试这个:

$string = "My new Tweet **#new** this is cool".
$linked_string = preg_replace('/\*\*(\#(.*?))\*\*/', '<a href="http://twitter.com/search/$1">$2</a>', $string);
于 2012-04-23T14:37:35.720 回答
1

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

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

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

于 2012-04-23T14:35:50.673 回答
1

这可能会这样做:

$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);
于 2012-04-23T14:37:32.860 回答