0

Assume I have a array like this:

$check="Ninja Turtles";
$key=array("jack and jil","peter likes pan","Ninja Turtles");

I want to find whether the keywords 'Ninja Turtels' in the $check variable exist in the ARRAY and if so I want to know in which INDEX of the ARRAY it exists in. My above code works perfectly fine, but what if my $check variables has some extra words like:

$check="Ninja blah bleh Turtles"

My code won't work then. I want to ignore the 'blah bleh' words in my string.

I managed to work around it with Python because I have years of experience in python but I am new to php.

My Code

foreach (array_values($key) as $i => $val) {
    $pos = strpos($check, $val);
    if ($pos === false) {
           echo "The string '$chechk' was not found in the ARRAY";
    } else {
            echo "Found '$check' at Postion: '$i'";


       }

  }

My Full Python Code

check="Ninja bleh balah Turtles"
key=["jack and jil","peter likes pan","Ninja Turtles"]
for index, name in enumerate(KEY):
     if(name in phrase):
         print("Found", name +" Index is ", index)
         active="Found", name +" Index is ", index
         break
     else:
         newkey=name.split()
         newphrase=check.split()
         num = 2
         l = [i for i in newkey if i in newphrase]
         if len(l) >= num:
             print('Found', name +" "+ "Index is", index)
             active="Found", name +" Index is ", index
             break
1
  • It looks like you used $chechk when you meant $check. Commented Jul 23, 2017 at 20:53

4 Answers 4

1

Similar php code is:

$check = "Ninja bleh balah Turtles";
$key = ["jack and jil", "peter likes pan", "Ninja Turtles"];

foreach($key as $index => $name) {
    if ($name === $check) {
        echo "Found $name Index is $index";
        return;
    } else {
        $newKey = explode(' ', $name);
        $newPhase = explode(' ', $check);
        $num = 2;
        $l = array_filter($newKey, function ($nkey) use ($newPhase) {
            return in_array($nkey, $newPhase);
        });
        if (count($l) >= $num) {
            echo "Found $name Index is $index";
            return;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Simple, and perfect!
1

Something like this should help you get started... https://iconoun.com/demo/temp_elo.php

<?php // demo/temp_elo.php
/**
 * Working with substrings
 *
 * https://stackoverflow.com/questions/45267396/accessing-substrings-in-a-php-array
 */
error_reporting(E_ALL);
echo '<pre>';


$target = "Ninja blah Turtles";
$source = [ "jack and jil", "peter likes pan", "Ninja Turtles" ];

// SEPARATE THE TARGET INTO ITS SUBSTRINGS
$targets = explode(' ', $target);

// TEST EACH OF THE SOURCE STRINGS
foreach ($source as $string)
{
    echo PHP_EOL . $string;
    foreach ($targets as $tgt)
    {
        if (stripos($string, $tgt) !== FALSE)
        {
            echo " CONTAINS $tgt";
        }
    }
}

Comments

1

Instead of matching check with array I do it the other way around with preg_match.

$check="Ninja blah bleh Turtles";
$key=array("jack and jil","peter likes pan","Ninja Turtles");

Foreach($key as $k => $val){
    $pattern = "/" . Implode("|", explode(" ",$val)) . "/";
    //Echo $pattern;
    If(preg_match($pattern, $check)) echo $k;
}

Output:

2 //as in $key[2] is where it matches.

https://3v4l.org/duYpU

Explode the "Ninja Turtles" to array and put them back together with | in-between (regex or).
Then add / to complete the regex pattern.
Check if this pattern matches $check.
If true echo key value.

Edit; while doing the dishes I realized $pattern can be done like this instead.

$pattern = "/" . Str_replace(" ", "|", $val) ."/";

It just replace space with regex or instead of exploding and imploding. Probably not much performance difference but it's more correct way to do it.

Comments

1

Try with tis:

$check = "Ninja bleh bleh Turtles";
$key = array("jack and jil","peter likes pan","Ninja Turtles");

foreach ($key as $k => $keyValue) {
    foreach (explode(' ', $check) as $valueCheck) {
        if (strstr($keyValue, $valueCheck)) {
            printf('[%s => %s]', $k, $keyValue);
            break;
        }
    }
}

Result:

[2 => Ninja Turtles]

But you can use array_filter()

$check = "Ninja bleh bleh Turtles";
$key = array("jack and jil","peter likes pan","Ninja Turtles");

$found = array_filter($key, function($value) use($check) {
    return array_filter(explode(' ', $check), function($valueKey) use($value) {
        return strstr($value, $valueKey);
    });
});

print_r($found);

Result:

Array
(
    [2] => Ninja Turtles
)

Or use preg_grep() and reg expressions:

$check = "Ninja bleh bleh Turtles";
$key = array("jack and jil","peter likes pan","Ninja Turtles");

$pattern = '/' . str_replace(' ', '|', $check) . '/';
$foundbyRegex = preg_grep($pattern, $key);

print_r($foundbyRegex);

Result:

Array
(
    [2] => Ninja Turtles
)

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.