-1

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

example

"gkshgksguvjvjvvjgvjgvjgvgdkguSTACKksbegkbeskbgksebgkbbOVERFLOWghbhjjhvjvjvjvjgvgjvgjvgjvgjvjgvgjvgjvgjvjgSTACKksbbbOVERFLOWvjvvvgjvgvgjvgjvgjvgjvvsdkgfkdgdgfdsgkhsdgdgfdsgffsdhkg"

  1. I want to extract "STACKksbegkbeskbgksebgkbbOVERFLOW"
    from the above text,

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

  3. if there are more than one satcks and overflows 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

1 Answers1

2
$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/'

BareNakedCoder
  • 3,257
  • 2
  • 13
  • 16