4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

twitter ハッシュタグ メンション URLを 正規表現で取得、削除 php

Last updated at Posted at 2018-05-08

いろいろなところに情報あるけど、改行がバグったりしてうまく動かない。
ということで今回は

・マッチしたものを取得したい
・マッチしたものを置き換えたい

の2つしたいので、処理を別にする。

まずは正規表現でハッシュタグ、メンションをそれぞれ取得


function getHashtags($tweet)
{
    $matches = array();
    preg_match_all('/#(w*[一-龠_ぁ-ん_ァ-ヴーa-zA-Za-zA-Z0-9]+|[a-zA-Z0-9_]+|[a-zA-Z0-9_]w*)/', $tweet, $matches);

    return $matches[0];
}

function getMentiontags($tweet)
{
    $matches = array();
    preg_match_all('/@(w*[一-龠_ぁ-ん_ァ-ヴーa-zA-Za-zA-Z0-9]+|[a-zA-Z0-9_]+|[a-zA-Z0-9_]w*)/', $tweet, $matches);

    return $matches[0];
}


置き換える


$hash_tags = getHashtags($profile->body);
$mention_tags = getMentiontags($profile->body);

$okikae = $profile->body;

foreach ($hash_tags as $v) {
    $okikae = str_replace($v,'<a href="https://twitter.com/search/?q='.urlencode($v).'" target="_blank">'.$v.'</a>',$okikae);
}

foreach ($mention_tags as $v) {
    $okikae = str_replace($v,'<a href="https://twitter.com/'.str_replace("@","",$v).'" target="_blank">'.$v.'</a>',$okikae);
}

削除

置き換えでなく、削除したい場合。
上記を関数にしただけ。


//    ハッシュタグを削除
public static function removeHashTag($data)
{
    preg_match_all('/#(w*[一-龠_ぁ-ん_ァ-ヴーa-zA-Za-zA-Z0-9]+|[a-zA-Z0-9_]+|[a-zA-Z0-9_]w*)/',  $data, $matches);
    foreach ($matches[0] as $s) {
    $data = str_replace($s,'',$data);
}

return $data;
}

//    メンションを削除
public static function removeMention($data)
{
    preg_match_all('/@(w*[一-龠_ぁ-ん_ァ-ヴーa-zA-Za-zA-Z0-9]+|[a-zA-Z0-9_]+|[a-zA-Z0-9_]w*)/',  $data, $matches);
    foreach ($matches[0] as $s) {
        $data = str_replace($s,'',$data);
    }

    return $data;
}

//    URLを削除
public static function removeURL($data)
{
    $pattern ='@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
    preg_match_all($pattern, $data, $matches);
    
    foreach ($matches[0] as $s) {
        $data = str_replace($s,'',$data);
    }

    $data = trim(preg_replace('/(?:\n|\r|\r\n)/', '', $data));
    
    return $data;
}

こんな感じです。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?