Link to home
Start Free TrialLog in
Avatar of johnsonallstars
johnsonallstars

asked on

PHP implode array and list results with some logic

Hello,

I am working with an array and would like to retrieve a list of results from the strings.  This is just test data, I am doing this to learn more about arrays and would like to return results based on the logic below (//logic in comments).

Thank you

Data:
"The Cat ran with the hat."
"The bat had a cat."
"The rat sat on the Bat!"

Results after logic:
"bat"
"cat"
"hat"
"ran"
"rat"
"sat"

<?php

$myArr = Array("The Cat ran with the hat.",
"the bat had a cat.",
"The rat sat on the Bat!");

//implode $myArr

//for each $myArr

//remove any unwanted strings
//not sure what is better preg_replace or str_replace.  If no regEx, I've read that string replace is better?
//unwanted strings - regardless of upper/lower case
$not_these_str("The",
" with ",
" had ",
" a ",
" on ",
"!",
"."
)


//$results = remove any duplicates from results

//$results = arrange alphanumeric

echo $results;

?>

//trying for these as results:

"bat"
"cat"
"hat"
"ran"
"rat"
"sat"
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Please see: http://iconoun.com/demo/temp_johnsonallstars.php
<?php // demo/temp_johnsonallstars.php

/**
 * http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28676605.html
 */
error_reporting(E_ALL);
echo '<pre>';

// AGGREGATE THE RESULTS IN THIS ARRAY
$m = [];

// THE TEST DATA
$data = <<<EOD
"The Cat ran with the hat."
"The bat had a cat."
"The rat sat on the Bat!"
EOD;

// THE ARRAY OF STOPWORDS
$not_these =
[ "the"
, "with"
, "had"
, "a"
, "on"
]
;
// NORMALIZE THE DATA
$data = strtolower($data);
$data = preg_replace('/[^a-z ]/', ' ', $data);
$data = preg_replace('/\s+/', ' ', $data);
$data = trim($data);
$data = explode(' ', $data);

// ACTIVATE THIS TO CHECK THE NORMALIZATION
// var_dump($data);

// REMOVE STOPWORDS
foreach ($data as $key => $str)
{
    if (in_array($str, $not_these)) unset($data[$key]);
}

// KEEP ONLY THE SORTED LIST OF WORDS
$data = array_unique($data);
sort($data);
print_r($data);

Open in new window

Avatar of johnsonallstars
johnsonallstars

ASKER

Hi Ray..

Your result worked great for me.  How would it differ in an array vs. the <<<EOD. syntax that you have?

As the EOD syntax  it is working, but when I set to an array.. I get this error

strtolower() expects parameter 1 to be string, array given ….on line 28

$data = array(
"The Cat ran with the hat.",
"The bat had a cat.",
"The rat sat on the Bat!"
);
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Very nice.  Ok..   Yes, worked both ways!

Thanks again!!
Thanks for the points and thanks for using E-E!  Best regards, ~Ray