检查字符串是否包含字符串末尾的一组字符

Check if a string contains a set of characters at the end of a string

我有一个简单的问题,却变成了一个棘手的问题:

$variable="This is some text***";

if (strpos($variable,'*') !== false) {
   echo 'found *';
} else {
   echo 'not found *';
}

但是不管有多少*,它都会在文本中找到一个*

我想让它只能通过搜索指定的星找到,***(三颗星)而不是 *(一颗星)。

为了让它匹配更严格,你只希望它匹配字符串末尾包含 *** 的字符串你可以使用正则表达式,所以,

if (preg_match('~[^*]\*{3}$~', $str)) {
    print "Valid";
}

这就是说,当字符串末尾有 3 颗星并且这 3 颗星之前没有星号时,它就是真的。将 3 更改为 21 或您想要匹配的任意数量的星星。

[^*]表示可以有一个字符,但不能是后面跟着3星的星。 \*{3} 表示它将匹配 3 颗星。反斜杠是为模式匹配转义星号,3 是总星数。

可以是这样的函数:

function starMatch($str, $count) {
    return (bool)preg_match('~[^*]\*{'.$count.'}$~', $str);
}

然后这样调用:

starMatch($str, 1);  // matches *
starMatch($str, 2);  // matches **
starMatch($str, 3);  // matches ***