我正在设计一个网站与评论系统,我想像一个Twitter的回复系统。PHP替换字符串帮助
如果用户放置@a_registered_username,我希望它成为用户配置文件的链接。
我认为preg_replace是这个所需的功能。
$ ALL_USERS_ROW * ['USERNAME']是所有用户的数据库查询数组,['USERNAME']是用户名行。
$内容是包含@username
我觉得这不应该是很难解决的人谁是擅长PHP的注释。
有没有人有任何想法如何做到这一点?
我正在设计一个网站与评论系统,我想像一个Twitter的回复系统。PHP替换字符串帮助
如果用户放置@a_registered_username,我希望它成为用户配置文件的链接。
我认为preg_replace是这个所需的功能。
$ ALL_USERS_ROW * ['USERNAME']是所有用户的数据库查询数组,['USERNAME']是用户名行。
$内容是包含@username
我觉得这不应该是很难解决的人谁是擅长PHP的注释。
有没有人有任何想法如何做到这一点?
你希望它去通过文字,并得到它,这里是一个很好的起点:
$txt='this is some text @seanja';
$re1='.*?'; # Non-greedy match on filler
$re2='(@)'; # Any Single Character 1
$re3='((?:[a-z][a-z]+))'; # Word 1
if ($c=preg_match_all ("/".$re1.$re2.$re3."/is", $txt, $matches))
{
$c1=$matches[1][0];
$word1=$matches[2][0]; //this is the one you want to replace with a link
print "($c1) ($word1) \n";
}
与生成:
http://www.txt2re.com/index-php.php3?s=this%20is%20some%20text%[email protected]&-40&1
[编辑]
其实,如果你去这里(http://www.gskinner.com/RegExr/),并在右侧的社区标签中搜索twitter,你会发现一些非常好的解决方案来解决这个问题:
$mystring = 'hello @seanja @bilbobaggins [email protected] and @slartibartfast';
$regex = '/(?<[email protected])((\w+))(\s)/g';
$replace = '<a href='http://twitter.com/$1' target="_blank">$1</a>$3';
preg_replace($regex, $replace, $myString);
$content = preg_replace("/\[email protected](\w+)\b/", "http://twitter.com/$1", $content);
应该工作,但我不能让字边界的比赛在我的测试工作...也许依赖于PHP
$content = preg_replace("/(^|\W)@(\w+)(\W|$)/", "$1http://twitter.com/$2$3", $content);
的版本中使用的正则表达式库测试并确实工作
$str = preg_replace('~(?<!\w)@(\w+)\b~', 'http://twitter.com/$1', $str);
不符合电子邮件。不匹配它周围的任何空间。
测试正则表达式模式的一个好方法是:http://www.gskinner.com/RegExr/,我通常从http://www.txt2re.com/生成一个基本模式开始 – SeanJA 2010-04-07 04:56:18