Terry
Terry

Reputation: 55

Get the word before and after a certain word?

The children likes to watch the cartoon Tom and Jerry but not Dora the Explorer!

I want to get the first and last word after "and" so the above would have an output of: Tom and Jerry

I have considered using the explode function using and as a delimiter but would get everything to the left and right of and.

  $string="The children likes to watch the cartoon Tom and Jerry but not Dora the Explorer!";

  list($left,$right)=explode('and',$string);

  echo $left; //The children likes to watch the cartoon Tom
  echo $right; //Jerry but not Dora the Explorer!

I thought I found a solution but it was written for C#.

Upvotes: 0

Views: 436

Answers (2)

user3634933
user3634933

Reputation: 145

Couldn't you just explode the $left and $right into arrays using space as delimeter, or something along those lines

$arrayLeft = explode(' ', $left);
$arrayRight = explode(' ', $right);

then do a count array for the left to get the last word

$countArray = count($arrayLeft);
$countArray--;//or whatever syntax to make it minus 1

then you have

$arrayLeft[$countArray]// for Tom
$arrayRight[0]// for jerry

Upvotes: 0

Saty
Saty

Reputation: 22532

You can you this expression //pass your string and match in this expression

$string="The children likes to watch the cartoon Tom and Jerry but not Dora the Explorer!";//this is your string
$find="and";//word to match
preg_match("!(\S+)\s*$find\s*(\S+)!i", $string, $match);
echo $before = $match[1];
echo $after = $match[2];

Upvotes: 1

Related Questions