0

I want to find the no of occurences of a sustring(pattern based) inside another string. For example:

$mystring = "|graboard='KERALA'||graboarded='KUSAT'||graboard='MG'";

I want to find the no of graboards present in the $mystring,

So I used the regex for this, But how will I find the no of occurrence?

3 Answers 3

3

If you must use a regex, preg_match_all() returns the number of matches.

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

Comments

0

Use preg_match_all:

$mystring = "|graboard='KERALA'||graboarded='KUSAT'||graboard='MG'";

preg_match_all("/(graboard)='(.+?)'/i", $mystring, $matches);

print_r($matches);

will yield:

Array
(
    [0] => Array
        (
            [0] => graboard='KERALA'
            [1] => graboard='MG'
        )

    [1] => Array
        (
            [0] => graboard
            [1] => graboard
        )

    [2] => Array
        (
            [0] => KERALA
            [1] => MG
        )

)

So then you can use count($matches[1]) -- however, this regex may need to be modified to suit your needs, but this is just a basic example.

Comments

0

Just use preg_match_all():

// The string.
$mystring="|graboard='KERALA'||graboarded='KUSAT'||graboard='MG'";

// The `preg_match_all()`.
preg_match_all('/graboard/is', $mystring, $matches);

// Echo the count of `$matches` generated by `preg_match_all()`.
echo count($matches[0]);

// Dumping the content of `$matches` for verification.
echo '<pre>';
print_r($matches);
echo '</pre>';

Comments

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.