Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use php regular expression

Tags:

string

regex

php

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.

like image 933
lewis machilika Avatar asked Jan 18 '26 12:01

lewis machilika


1 Answers

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.

like image 83
Wiktor Stribiżew Avatar answered Jan 20 '26 03:01

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!