我想从我正在从twitter上检索的推文中解析主题标签。现在,我在api中找不到任何可用的东西。所以,我正在使用php自己解析它。我尝试过几件事。
<?php
$subject = "This is a simple #hashtag";
$pattern = "#\S*\w";
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
我也试过了
$pattern = "/[#]"."[A-Za-z0-9-_]"."/g";
但后来它显示/ g不被php识别。我一直试图这么做很长一段时间但是我无法做到这一点。所以请帮忙。
附: :我对正则表达式的想法很少。
您需要考虑标签可能出现的位置。有三种情况:
所以这将正确匹配它们:
'/(^|\s)\#\w+/'
说明:
^
可用于OR语句\s
用于捕捉空格,制表符和新行这是完整的代码:
<?php
$subject = "#hashtag This is a simple #hashtag hello world #hastag2 last string not-a-hash-tag#hashtag3 and yet not -#hashtag";
$pattern = "/(?:^|\s)(\#\w+)/";
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
这对我有用:
$subject = "This is a simple #hashtag hello world #hastag2 last string #hashtag3";
$pattern = "/(#\w+)/";
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
使用对象原型有一种更简单的方法,写了一篇文章详细说明了如何使用hastags,以及推文中的用户名和URL。 a project需要它我正在努力从Twitter API获取推文。
https://benmarshall.me/parse-twitter-hashtags/
这是相关的代码:
// Auto-link URLs in a string
// Usage: mystring.parseURL()
String.prototype.parseURL = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function( url ) {
return url.link( url );
});
};
// Auto-link Twitter usernames in a string
// Usage: mystring.parseUsername()
String.prototype.parseUsername = function() {
return this.replace(/[@]+[A-Za-z0-9-_]+/g, function( u ) {
var username = u.replace("@","");
return u.link( 'http://twitter.com/' + username );
});
};
// Auto-link Twitter hashtags in a string
// Usage: mystring.parseHashtag()
String.prototype.parseHashtag = function() {
return this.replace(/[#]+[A-Za-z0-9-_]+/g, function( t ) {
var tag = t.replace("#","%23");
return t.link( 'http://search.twitter.com/search?q=' + tag );
});
};