$word = file('list.txt');
$content = file_get_contents('fleetyfleet.txt');
fleetyfleet.txt contains
DimensionNameGreenrandomjunktextextcstuffidonwantDimensionNameBluemoreeecrapidontwannaseeeDimensionNameYellowDimensionNameGrayrandomcrapDimensionNameRed
list.txt contains
Green Blue Yellow
what i want is to be able to find DimensionName then store the word after it into an array if the word is in list.txt
so when script was ran the result stored in array would be Green,Blue,Yellow but not Red and Gray because they are not in our list
The trick is to explode()
your file contents by delimiter and then filter results with the words from the list. $matching
contains all found fragments matching list.
$words = file_get_contents('list.txt');
$text = file_get_contents('content.txt');
$elements = explode('DimensionName', $text); // trick
$words = explode(' ', $words); // words list
// leverage native PHP function
$matching = array_reduce($elements, function($result, $item) use($words) {
if(in_array($item, $words)) { $result[] = $item; }
return $result;
}, array());
var_dump($matching);
UPDATE
array_reduce()
is a neat function, but I totally forgot about a way simpler solution:
$matching = array_intersect($words, $elements);
From the docs:
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
So $matching
will contain all elements from $words
array that are present in $elements
. This is the simplest and possibly the best solution here.
Explode your word list, then loop over it:
$word = file_get_contents('list.txt');
$content = file_get_contents('fleetyfleet.txt');
$found_dimensions = array(); // our array
$word_array = explode(' ', $word); // explode the list
foreach($word_array as $one_word) { // loop over it
$str = 'DimensionName'.$one_word; // what are we looking for?
if(strstr($content, $str) !== false) { // look for it!
echo "Found $one_word<br/>"; // Just for demonstration purposes
$found_dimensions[] = $one_word; // add to the array
}
}
I think this is what you wanted..I loop through each word in list.txt
, and then use a preg_match()
to see if that dimension is in fleetyfleet.txt
(you don't need a regex for my example, but I left it in case your example is more complicated). If it matches, then I add the match to your array of $dimensions
.
<?php
$dimensions = array();
$content = 'DimensionNameGreenrandomjunktextextcstuffidonwantDimensionNameBluemoreeecrapidontwannaseeeDimensionNameYellowDimensionNameGrayrandomcrapDimensionNameRed';
$list = 'Green Blue Yellow';
foreach(explode(' ', $list) as $word) {
if(preg_match('/DimensionName' . trim($word) . '/', $content, $matches) {
$dimensions[] = reset($matches);
}
}
var_dump($dimensions);
// array(3) {
// [0]=> string(18) "DimensionNameGreen"
// [1]=> string(17) "DimensionNameBlue"
// [2]=> string(19) "DimensionNameYellow"
// }