You don't need to do anything about spaces, because they're removed by explode(). To get rid of non-word characters at the end of each word, use the regex metacharacter for a word character (\w). This matches A-Z, a-z, 0-9, and the underscore. You should also add the hyphen. So, this would do it:
foreach ($words as $word) {
preg_match('/^([-\w]+)/', $word, $m);
echo $m[1] . '<br />';
}
If you want to exclude numbers and the possibility of underscores, change the regex to this:
foreach ($words as $word) {
preg_match('/^([-A-Za-z]+)/', $word, $m);
echo $m[1] . '<br />';
}
Don't despair over the time it has taken you. My knowledge of PHP has been built up over eight or nine years. I don't have the benefit of an education in computer science, either. So I didn't have a running start.
What I have discovered is that the best way to approach a problem is by breaking it down into small steps. Instead of thinking in terms of code, I think in terms of what I want to happen. It helps if you start out with a skeleton of comments:
// do this
// then do this
// if (condition A) {
// do one thing
} elseif (condition B) {
// do something else
} else {
// do something completely different
}
I then work on each section separately until I get it right. Sometimes, I end up with a solution that works, but is rather complex. So, I then see if there are ways to simplify it. When creating this solution for you, I first gathered the words into a multidimensional array, which involved a complex loop to access the individual words. It worked, but I thought there must be a simpler way of gathering the words into a simple array in the first place. It took a couple of attempts before I hit on array_merge(). Initially, I used array_push(), but that still created a multidimensional array.
One very important technique is to use echo or print_r() to examine the results of a function or loop. It helps enormously if you can see the results of each stage of the operation.
The rest simply comes down to a lot of reading. When I first started doing PHP, I bought "Programming PHP" by Rasmus Lerdorf and Kevin Tatroe. It's not an easy book to sit down and read from cover to cover, because it's rather like a grammar book. However, I did read the first half of the book to get an overview of the core features of the language. Since then, I keep it close at hand. It's one of the most heavily-thumbed and dog-eared books in my collection. You don't even need a copy of the book. If you go through the Strings and Arrays sections of the PHP online manual, you will learn a huge amount of useful material. I don't keep everything in my head, but I usually know where to look up details of the function I'll need.
Keep at it. You'll get there in the end.