求一正则表达式 #hashtag

cs5276 2011-09-08 01:41:21
找出一段文本内的#hashtags,现在只能抓到由英文字母组成、以及以字母或数字结尾的tags(如 #中1)
请各位大大帮忙写出可以包含纯中文的hashtag(#论坛 #google #csdn论坛 #使用google)

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head><body>
<h1>Get Hashtags</h1>
<?php
$subject = "捣乱的字符#tags #tagging #中文 #csdn论坛 #使用google google #143 #中1 #1中";
$pattern = '%((?:\A|(?<=\s))(?:#|@)(\w|(\p{L}\p{M}?))+\b)|(\[(#|@)[^\]]+\])%u';
preg_match_all($pattern, $subject, $matches);
$words = $matches[0];
print_r($words);
?>
</body>
</html>

谢谢各位!
...全文
318 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
木目子 2011-09-08
  • 打赏
  • 举报
回复
$subject = "捣乱的字符#tags #tagging #中文 #csdn论坛 #使用google google #143 #中1 #1中";
preg_match_all('|(#[^\s]+\s+)|suU',$subject.' ',$match,PREG_PATTERN_ORDER);
print_r($match);

cs5276 2011-09-08
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 jordan102 的回复:]

PHP code

$subject = "捣乱的字符#tags #tagging #中文 #csdn论坛 #使用google google #143 #中1 #1中";
$pattern = '/#.+(?:[\s]{1}|$)/Um';
preg_match_all($pattern, $subject, $matches);
print_r($matches[0]);
[/Quote]

这段很有用,非常感谢你的帮助!不知高人能否再帮忙优化一下?
如果$subject是这样

$subject = "#tags#tag #中文已经#能支持了";

目前的代码返回的数组中会包含两个结果:#tags#tag #中文已经#能支持了
如果想把"#tags#tag"提取为两个结果"#tags、#tag"该如何做呢?
谢谢!
一起混吧 2011-09-08
  • 打赏
  • 举报
回复

$subject = "捣乱的字符#tags #tagging #中文 #csdn论坛 #使用google google #143 #中1 #1中";
$pattern = '/#.+(?:[\s]{1}|$)/Um';
preg_match_all($pattern, $subject, $matches);
print_r($matches[0]);
cs5276 2011-09-08
  • 打赏
  • 举报
回复
再看看有没有更好的解决办法,只改$pattern部分。
黄袍披身 2011-09-08
  • 打赏
  • 举报
回复
定你一下 咔咔 对正则不是很熟悉 等明天乔丹 怪蜀黍 妖怪之类正则高人的来了给你回帖。。。睡觉去也
cs5276 2011-09-08
  • 打赏
  • 举报
回复
补充,目前能输出的结果:

Array ( [0] => #tagging [1] => #csdn [2] => #使用google [3] => #143 [4] => #中1 [5] => #1 )


想要的结果:

Array ( [0] => #tagging [1] => #中文 [2] => #csdn论坛 [3] => #使用google [4] => #143 [5] => #中1 [6] => #1中 )


再次谢谢各位

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧