View Full Version : Eliminating an element from an array ?

11-05-2009, 04:37 PM

In my array of words, I sometimes get some gibberish and sometimes get
"words" that are just a space.

To eliminate them I have chosen a rather arbitrary word length of 25 characters. Anything over that is probably not a real word.

My words are in a string,
so I get my word list into an array with this:

$words = explode(" ", $text);

Before doing that I would like to get rid of
those long words and the single-space-only words

I guess that I need a regex
(or two of them )

$regex = " ??? ";
$text = preg_replace($regex,"",$text);

Any ideas what the regex(s) should be ?


11-05-2009, 05:40 PM
I never use code I don't understand. I would recommend the same to you. If someone else writes regex that you just plug in with no idea how it's working, it will be impossible for you to maintain that code.

So, there are plenty of ways to do this without any regex. In my opinion, the simplest way is the best way. I would loop through the array, check each element, unset it if it doesn't pass your validation rules.

foreach($myArray as $key => $val) {
if (strlen($val) > 25) {

11-06-2009, 06:55 AM
I totally agree with you,
regex is something that I am rather weak on and
I am trying to get my head around.

Most of my posts recently have been about regex so
hopefully I will pick it up.

On good thing about doing that loop is that I could check
for other things at the same time.

Presumably I can get rid of those one-space words
at the same time with:

foreach($myArray as $key => $val) {
if (strlen($val) > 25 || $val == " " || $val == "" ) {

11-06-2009, 08:33 AM
You could use an array_filter to capture just what you're looking for:

function myArrayFilter($var)
$var = trim($var);
return !empty($var) && strlen($var) < 25;

$newArray = array_filter($myArray, 'myArrayFilter');

Try that, does that work?

Looks like the 25 character max is a pretty good assumption. Check this wiki link (don't know how valid it is...), but it shows aside from 7 pretty much unheard of words that cover the 27+ characters.

Guess you'll want that link lol: http://en.wikipedia.org/wiki/Longest_word_in_English