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


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 ***