2

I've taken a look around but cant seem to find anything that does as needed.

Lets say I have 2 arrays in a function, however they are completely dynamic. So each time this function is run, the arrays are created based on a page that has been submitted.

I need to some how match these arrays and look for any phrase/words that appear in both.

Example: (with only a single element in each array)

    Array 1: "This is some sample text that will display on the web"
    Array 2: "You could always use some sample text for testing"

So in that example, the 2 arrays have a phrase that appears exactly the same in each: "Sample Text"

So seeing as these arrays are always dynamic I am unable to do anything like Regex because I will never know what words will be in the arrays.

4 Answers 4

4

You could find all words in an array of strings like this:

function find_words(array $arr)
{
        return array_reduce($arr, function(&$result, $item) {
                if (($words = str_word_count($item, 1))) {
                        return array_merge($result, $words);
                }
        }, array());
}

To use it, you run the end results through array_intersect:

$a = array('This is some sample text that', 'will display on the web');
$b = array('You could always use some sample text for testing');

$similar = array_intersect(find_words($a), find_words($b));
// ["some", "sample", "text"]
Sign up to request clarification or add additional context in comments.

1 Comment

Jack, this seems to have done the trick. Thank you, I didn't realize array_intersect worked like this.
1

Array_intersect() should do this for you:

http://www.php.net/manual/en/function.array-intersect.php

*array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.*

1 Comment

Maybe this could be an argumentation: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
0

maybe something like this:

foreach($arr as $v) {
   $pos = strpos($v, "sample text");
   if($pos !== false) {
        // success
   }

}

here is the manual: http://de3.php.net/manual/de/function.strpos.php

2 Comments

Hi Steven, this would work however the array is dynamic so I would never know what words I am trying to match.
but you will be able to use another variable for argument 2 of strpos
0

Explode the two strings by spaces, and it is a simple case of comparing arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.