3

I wanted to count asterisks from a string starting with foo 'fooarbazlujabazlewis*bazbazlewbaz' and i should be able to count asterisk from another string starting with luja in short I wanted the starting string to be changed programmatically

I tried below code, but it counts any asterisk even if foo is not at the beginning

preg_match_all('/(^foo\*)*(\*)/', '*foo*arbaz*luj*abaz*lewis*bazbazlewbaz'); 

the result is 6. but in this case, I wanted it to fail since foo is not at the beginning.

3
  • What is your expected output Commented Jun 26, 2021 at 14:06
  • it should only count when foo is at the beginning of the string Commented Jun 26, 2021 at 14:08
  • Why a regex ? : if ( strpos($str, 'foo') === 0 ) echo substr_count($str, '*'); Commented Jun 26, 2021 at 17:28

1 Answer 1

2

It is not the best application for a regex, but you can use

preg_match_all('~(?:\G(?!\A)|^foo)[^*]*\K\*~', $string, $matches)

See the regex demo. Details:

  • (?:\G(?!\A)|^foo) - either the end of the previous successful match or foo at the start of string
  • [^*]* - zero or more chars other than *
  • \K - discard the text matched so far
  • \* - an asterisk.

See the PHP demo:

$string = "foo*arbaz*luj*abaz*lewis*bazbazlewbaz";
echo preg_match_all('~(?:\G(?!\A)|^foo)[^*]*\K\*~', $string, $matches);
// => 5

Without a regex, you could simply check if foo appears at the start of string (using strpos) and then use substr_count to count the occurrences of asterisks:

$string = "foo*arbaz*luj*abaz*lewis*bazbazlewbaz";
if (strpos($string, "foo") === 0 ) {
    echo substr_count($string, "*");
}

See this PHP demo.

Sign up to request clarification or add additional context in comments.

2 Comments

Use always a strict comparison with strpos and 0, otherwise your condition will be true when foo isn't in the string.
@CasimiretHippolyte Thanks for noticing, I should have been more careful when reading the Warning section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.