Twitterのハッシュタグについてサポートが必要です。PHPで特定のハッシュタグを文字列変数として抽出する必要があります。今まで私はこれを持っています
$hash = preg_replace ("/#(\\w+)/", "<a href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet_text);
しかし、これはhashtag_stringをリンクに変換するだけです
preg_match()
次のように、ハッシュを識別して変数にキャプチャするために使用します。
$string = 'Tweet #hashtag';
preg_match("/#(\\w+)/", $string, $matches);
$hash = $matches[1];
var_dump( $hash); // Outputs 'hashtag'
この関数はあなたを助けると思います:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
私が理解しているように、テキスト/パーグラフ/投稿では、次のようなハッシュ記号(#)でタグを表示したいです:-#tagとURLでは、後の文字列#
がリクエストでサーバーに送信されないため、#記号を削除したいだから私はあなたのコードを編集してこれを試してみました:-
$string="www.funnenjoy.com is best #SocialNetworking #website";
$text=preg_replace('/#(\\w+)/','<a href=/hash/$1>$0</a>',$string);
echo $text; // output will be www.funnenjoy.com is best <a href=search/SocialNetworking>#SocialNetworking</a> <a href=/search/website>#website</a>
複数のハッシュタグを配列に抽出します
$body = 'My #name is #Eminem, I am rap #god, #Yoyoya check it #out';
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
preg_match_all()
PHP関数を使用できます
preg_match_all('/(?<!\w)#\w+/', $description, $allMatches);
ハッシュタグ配列のみを提供します
preg_match_all('/#(\w+)/', $description, $allMatches);
あなたにハッシュタグを与え、ハッシュタグ配列なしで
print_r($allMatches)
preg_match関数を使用して文字列の値を抽出できます
preg_match("/#(\w+)/", $tweet_text, $matches);
$hash = $matches[1];
preg_matchは、一致する結果を配列に格納します。ドキュメントを見て、それを操作する方法を確認する必要があります。
これを行うための非正規表現の方法は次のとおりです。
<?php
$tweet = "Foo bar #hashTag hello world";
$hashPos = strpos($tweet,'#');
$hashTag = '';
while ($tweet[$hashPos] !== ' ') {
$hashTag .= $tweet[$hashPos++];
}
echo $hashTag;
注:これは、ツイートの最初のハッシュタグのみを取得します。