简体   繁体   中英

how to find a specific set of letters in a block of letters in php

I need to extract some words in a set of letters , ,

example

"gkshgksguvjvjvvjgvjgvjgvgdkgu STACK ksbegkbeskbgksebgkbb OVERFLOW ghbhjjhvjvjvjvjgvgjvgjvgjvgjvjgvgjvgjvgjvjg STACK ksbbb OVERFLOW vjvvvgjvgvgjvgjvgjvgjvvsdkgfkdgdgfdsgkhsdgdgfdsgffsdhkg"

  1. I want to extract " STACK ksbegkbeskbgksebgkbb OVERFLOW "
    from the above text,

  2. number of letters between STACK and OVERFLOW can be vary.

  3. if there are more than one satck s and overflow s in the set of letters , I want to find them all with the letters inbetween those two words , (and add them to an array)

    each time , the number of letters in between STACK and OVERFLOW can be changed

$theBlob = "abcSTACKmmmOVERFLOWxyz...";
preg_match_all('/STACK(.*)OVERFLOW/U', $theBlob, $matches);
assert( $matches[0][0] === 'STACKmmmOVERFLOW' );
assert( $matches[1][0] === 'mmm' );

CORRECTED: Added U modifier to make .* non-greedy.

The regular express /STACK(.*)OVERFLOW/U has the U modifier to make .* non-greedy which means it should match the minimal number of characters (if no U , .* will be greedy and match as much as it can (up to the last "OVERFLOW").

$matches will be an array of arrays. $matches[0] is an array of all the full matches. $matches[1] contains an array of all sub-parts in the first set of parenthesis.

See http://phpfiddle.org/main/code/7cix-4y38

Note: the U modifier makes all repeaters non-greedy. If you want to mix greedy and non-greedy, you can do .*? to make just that one non-greedy. The regex above would become /STACK(.*?)OVERFLOW/'

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