简体   繁体   中英

Find all occurrences of a “unknown” substring in a string with PHP

I have a string and I need to find all occurrences of some substrings in it but I know only initials chars of substrings... Ho can I do?

Example:

$my_string = "This is a text cointaining [substring_aaa attr], [substring_bbb attr] and [substring], [substring], [substring] and I'll try to find them!";

I know all substrings begin with '[substring' and end with a space char (before attr) or ']' char, so in this example I need to find substring_aaa , substring_bbb and substring and count how many occurrences for each one of them.

The result would be an associative array with the substrings as keys and occurrerrences as values, example:

$result = array(
    'substring' => 3,
    'substring_aaa' => 1,
    'substring_bbb' => 1
)

Match [substring and then NOT ] zero or more times and then a ] :

preg_match_all('/\[(substring[^\]]*)\]/', $my_string, $matches);

$matches[1] will yield:

    Array
    (
        [0] => substring_aaa attr
        [1] => substring_bbb attr
        [2] => substring
        [3] => substring
        [4] => substring
    )

Then you can count the values:

$result = array_count_values($matches[1]);

After rereading the question, if you don't want what comes after a space (attr in this case) then:

preg_match_all('/\[(substring[^\]\s]*)[\]\s]/', $my_string, $matches);

For which $matches[1] will yield:

    Array
    (
        [0] => substring_aaa
        [1] => substring_bbb
        [2] => substring
        [3] => substring
        [4] => substring
    )

With the array_count_values yielding:

    Array
    (
        [substring_aaa] => 1
        [substring_bbb] => 1
        [substring] => 3
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM