1

所以我有一个功能,可以在我的网站上输出保存的推文,并且对于包含我想要链接<?=stripslashes($row['tweet_text'])?>的内容的推文。@user那么我将如何做到这一点,如果它找到了该字母@,那么它将连接到它的文本转换为一个链接,该链接将转到www.twitter.com/user

因此,如果它找到诸如此类的文本,@username它将使其成为链接

<a href="http://www.twitter.com/username">@username</a>

4

3 回答 3

3
<?= preg_replace('/@(\w+)/', '<a href="https://www.twitter.com/$1">@$1</a>', stripslashes($row['tweet_text']))?>

对于哈希标签:

<?= preg_replace('/#(\w+)/', '<a href="https://twitter.com/#!/search/$#$1">#$1</a>', stripslashes($row['tweet_text']))?>
于 2012-09-18T03:33:10.480 回答
1

这是你想要的:

<?php

$text = 'asd asd asd asd as @user aasda sad asd @yyy sd';

$text = preg_replace('/(.*?)\@([A-Za-z0-9_]+)(.*?)/', '$1<a href="http://www.twitter.com/$2">@$2</a>$3', $text);

?>

任何具有@+A-Za-z0-9_ 的内容都将更改为链接...

于 2012-09-18T03:35:30.350 回答
0

我想你可以做一个preg_match_all来获取用户名,假设用户名不包含任何空格:

$usernames = preg_match_all( "|\@(.*) |" , stripslashes($row['tweet_text']) , $match );

$usernames = $match[0];

//loop through usernames and do whatever (replace, get data, etc etc)

如果您只想用 替换所有用户名http://twitter.com/username,那么只需preg_replace在输出中使用:

preg_replace('|\@(.*)|', '<a href="http://www.twitter.com/$1">@$1</a>', stripslashes($row['tweet_text'])) 
于 2012-09-18T03:39:11.687 回答