user3369524
user3369524

Reputation: 41

php, get multiple sub string from a large string into an array

I want extract several strings of X length that start with specific string ex: 'Peter was [and then can be anything]' from a large string into an array like this

$myString = "Today Peter was in the zoo doin son and so on, 
    yesterday Peter was with Karen eating so on and so on, 
    the day before yesterday Peter was dead jesus christ AND THE STRING KEEP GOING";

$theResult = [
    'Peter was in the zoo....',
    'Peter was with Karen....',
    'Peter was dead....',
    etc...
]

The clue string is Peter was, and then the rest can be anything many times

Upvotes: 0

Views: 56

Answers (3)

Forge Web Design
Forge Web Design

Reputation: 835

You can use explode function to convert string to array like below

$myString = "Today Peter was in the zoo doin son and so on, 
    yesterday Peter was with Karen eating so on and so on, 
    the day before yesterday Peter was dead jesus christ AND THE STRING KEEP GOING";
   $exp=explode('Peter was',$myString);
   print_r($exp);

Upvotes: 0

Timothy Alexis Vass
Timothy Alexis Vass

Reputation: 2705

The answer after you changed the question:

$theResult = preg_split('/(?=Peter was)/', $myString);

Will give:

array(
  0 => Today
  1 => Peter was in the zoo doin son and so on, yesterday
  2 => Peter was with Karen eating so on and so on, the day before yesterday
  3 => Peter was dead jesus christ AND THE STRING KEEP GOING
)

Upvotes: 1

Timothy Alexis Vass
Timothy Alexis Vass

Reputation: 2705

This is the answer to the question you had before you changed it...

$myString = 'We are writing a string here and abc taking this string xcv we are going to extract ikw some text from it and put it in an array';

preg_match('/.*(abc.{10}).*(xcv.{10}).*(ikw.{10})/', $myString, $theResult);

Will put 4 items in $theResult. The 0th group which is all of them and then 1, 2, and 3 for the captures you want.

array(
  0 => We are writing a string here and abc taking this string xcv we are going to extract ikw some text
  1 => abc taking th
  2 => xcv we are go
  3 => ikw some text
)

Upvotes: 0

Related Questions