0

I'm new in PHP programming. I need your help to finish my homework.

I want to explode the following sentence: I love my band and my cat into arrays.

But I need to use space and word and as delimiters. So it should become like this:

$arr[0] -> I
$arr[1] -> love
$arr[2] -> my
$arr[3] -> band
$arr[4] -> my
$arr[5] -> cat

I have tried like this:

$words = "I love my band and my cat"
$stopwords = "/ |and/";
$arr = explode($stopwords, $words);

But the problem is, it also removes characters and from word band so it becomes like this:

$arr[0] -> I
$arr[1] -> love
$arr[2] -> my
$arr[3] -> b
$arr[4] -> my
$arr[5] -> cat

This is not what I want. I want to remove the word that exactly and, not word that contains and characters.

Is there anyway to solve this? Can anybody help me? Thank you very much.. :-)

Matt Busche
  • 14,216
  • 5
  • 36
  • 61
  • 1
    `explode` is for fixed strings. `split` and `preg_split` are for regexpressions like you tried. – mario Feb 20 '13 at 03:17
  • Since you've admitted this is homework I feel I cannot give you the answer. But i suggest you read this http://www.regular-expressions.info/tutorial.html. also, use preg_split, explode can't use regular expressions. – Galen Feb 20 '13 at 03:19
  • If the task is not about regex, a logic is to explode it first and then remove (unset) the unneeded elements. – rlatief Feb 20 '13 at 03:21
  • One way to look at the problem you are having is to think about what is different with `and` and `band`. Specifically whitespace. – Jim Feb 20 '13 at 03:36

2 Answers2

3

If you want to avoid splitting out and in the middle of a word, you have to filter the result list (array_diff), or use a more complex regex. Then also consider preg_match_all instead of splitting:

 preg_match_all('/  (?! \b and \b)  (\b \w+ \b)  /x', $input, $words);

This will only search for consecutive word-characters, instead of breaking up on spaces. And the assertion ?! will skip occurences of and.

mario
  • 144,265
  • 20
  • 237
  • 291
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Feb 20 '13 at 03:24
-4

Try this:

<?php
$words = "I love my band and my cat";
$clean = str_replace(" and",'',$words);
$array = explode(" ",$clean);
print_r($array);
?>
ionFish
  • 1,004
  • 1
  • 8
  • 20