检查hashtag是否位于字符串php的开头或中间


Check if hashtag is at the start OR middle of string php

我目前正在获取字符串(即推特)中的所有#标签。工作正常。

然而,我想找到只在字符串开头或字符串中间(或离字符串足够近)的标签。换句话说,找到所有不在字符串末尾的标签。

如果您还可以为我指明如何查看字符串末尾是否也存在标签的方向,则可获得加分

$tweet = 'This is an #example tweet';
preg_match_all('/(#'w+)/u', $tweet, $matches);  
if ($matches) { // found hashtag(s) }

// Check if Hashtag is last word; the strpos and explode way:
$tweet = 'This is an #example #tweet';
$words = explode(" ", $tweet);
$last_word = end($words);
// count the number of times "#" occurs in the $tweet.
// if # exists in somewhere else $exists_anywhere equals TRUE !!
$exists_anywhere = substr_count($tweet,'#') > 1 ? TRUE : FALSE ;
if(strpos($last_word,'#') !== FALSE  ) {
   // last word has #
}

来自文档:

如果只想检查一个字符串是否为包含在另一个字符串中。使用strpos()或strstr()将更快。

preg_match_all('/(?!#'w+'W+$)(#'w+)'W/', $tweet, $result);

这是一个#tweet用户将捕获#tweet

#推特用户的第二个示例将捕获#Second#tweet

##tweet的另一个例子将捕获#Another,但不会捕获#tweet(即使它以!.或任何其他非单词字符结尾)

我们快结束了,#是的不会捕获任何

最后一条#推特!晚安将捕获#tweet

当然,所有的hastags(捕获)都将存储在$result[1]

仅在开头匹配:

/^(#'w+)/

要查找特定的#标签:

/^#tweet/

要匹配中间的任何位置(不是开始或结束):

/^[^#]+(#'w+)[^'w]+$/

要查找特定的#标签:

/^[^#]+#tweet[^'w]$/

仅在最后匹配:

/(#'w+)$/

要查找特定的#标签:

/#tweet$/

好吧,我个人会把字符串变成一个单词数组:

$words = explode(' ', $tweet);

然后对第一个单词进行检查:

preg_match_all('/(#'w+)/u', $words[0], $matches);
if ($matches) {
    //first word has a hashtag
}

然后,您可以简单地遍历数组的其余部分,找到在中间的标签。最后检查最后一个单词,

$sizeof = count($words) - 1;
preg_match_all('/(#'w+)/u', $word[$sizeof], $matches);
if ($matches) {
    //last word has a hashtag
}

更新/编辑

$tweet = "Hello# It's #a# beaut#iful day. #tweet";
$tweet_arr = explode(" ", $tweet);
$arrCount = 0;
foreach ($tweet_arr as $word) {
    $arrCount ++;
    if (strpos($word, '#') !== false) {
        $end = substr($word, -1);
        $beginning = substr($word, 0, 1);
        $middle_string = substr($word, 1, -1);
        if ($beginning === "#") {
            echo "hash is at the beginning on word " . $arrCount . "<br />";
        }
        if (strpos($middle_string, '#') !== false) {
            $charNum = strpos($middle_string, '#') + 1;
            echo "hash is in the middle at character number " . $charNum . " on word " . $arrCount . "<br />";
        }
        if ($end === "#") {
            echo "hash is at the end on word " . $arrCount . "<br />";
        }
    }
}