Search code examples
phpregexstringpreg-match

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


I have a simple problem, but has become a troublesome problem:

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

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

But it will find a * in the text no matter how many *s there are.

I want to make it only can be found by searching specified star, *** (three stars) instead only * (one star).


Solution

  • To make it even more strict matching, that you only want it to match a string that contains *** at the end of the string you can use regex, so,

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

    What this says is when a string has 3 stars at the end and there are no asterisks before those 3 stars then it will be true. Change the 3 to a 2 or 1 or whatever number of stars you want to match.

    [^*] means that there can be a character but it cannot be a star that is followed by 3 stars. \*{3} means it will match 3 stars. The backslash is to escape asterisk for the pattern match and 3 is the number of total stars.

    It could be a function like this:

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

    And called like this:

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