微博开发之@替换示例代码
发布时间:2017-11-07 编辑:jiaochengji.com
在微博开发中,对于@的替换,很多人可能会用到正则吧,正则除了效率问题,还有误替换,这里分享一个例子,大家参考下。
举个例子,微博开发之@替换:
@ponyma可能被解析成了"@pony"+"ma"
代码:
复制代码 代码示例:
$users['pony'] = '马化腾';
$users['ponyma'] = '坡泥马';
$users['ponyli'] = '坡泥李';
$text = "@pony:特别声明,@ponyli@ponyma@ponywong@ponylao什么的都不是我";
preg_match_all('/@\w+/', $text, $matches);
if(is_array($matches[0]) && !empty($matches[0])){
$replaces = array_combine($matches[0], $matches[0]);
}
foreach($users as $userid=>$username){
$replaces['@'.$userid] = "<a href='http://t.qq.com/{$userid}'>{$username}</a>";
}
$html = strtr($text, $replaces);
echo $html;
$users['ponyma'] = '坡泥马';
$users['ponyli'] = '坡泥李';
$text = "@pony:特别声明,@ponyli@ponyma@ponywong@ponylao什么的都不是我";
preg_match_all('/@\w+/', $text, $matches);
if(is_array($matches[0]) && !empty($matches[0])){
$replaces = array_combine($matches[0], $matches[0]);
}
foreach($users as $userid=>$username){
$replaces['@'.$userid] = "<a href='http://t.qq.com/{$userid}'>{$username}</a>";
}
$html = strtr($text, $replaces);
echo $html;
结果:
<a href=’http://t.qq.com/pony’>马化腾</a>:特别声明,<a href=’http://t.qq.com/ponyli’>坡泥李</a><a href=’http://t.qq.com/ponyma’>坡泥马</a>@ponywong@ponylao什么的都不是我
您可能感兴趣的文章:
微博开发之@替换示例代码
php使用新浪微博API开发用户授权功能
h5元素/属性/格式化的详细介绍
PHP流程控制的替代语法示例
PHP替换字符串(只替换首个字符串)
微信公众平台开发入门教程
php添加关联链接的代码
php获取新浪微博数据API的实例代码
python3中re函数如何进行替换?
详解如何通过H5唤起本地app
上一篇:php访问控制面试题一例
下一篇:微博短链接算法的php实现版本
[关闭]