2

My problem is that I have a huge array. In this array are the Browser, the user used to get on my website, but also bots and spiders.

It looks like this: Mozilla, Mozilla, Mozillabot, Mozilla, Unicornbot and so on.

I need to get every key in my array, that have 'bot' in it like mozillabot, unicornbot.
But I cant find something.

array_search doesn't work, array_keys too.

Does anyone know a solution in Laravel?

2
  • Can you update your question to include a small sample of your array and the expected result? Ex. you want as a result an array with all the bots or something similar. Commented Nov 17, 2015 at 10:07
  • Look at the array_filter() function Commented Nov 17, 2015 at 10:17

4 Answers 4

1

You can use the Crawler Detect library which makes it really easy to identify bots/crawlers/spiders. It can be as simple as a couple of lines of code. Below is a snippet taken from the library's documentation:

use Jaybizzle\CrawlerDetect\CrawlerDetect;

$CrawlerDetect = new CrawlerDetect;

// Check the user agent of the current 'visitor'
if($CrawlerDetect->isCrawler()) {
    // true if crawler user agent detected
}

// Pass a user agent as a string
if($CrawlerDetect->isCrawler('Mozilla/5.0 (compatible; Sosospider/2.0; +http://help.soso.com/webspider.htm)')) {
    // true if crawler user agent detected
}
Sign up to request clarification or add additional context in comments.

1 Comment

You can wrap the isCrawler() check in the callback of array_where. Nice! +1
0

You could do something like this...

$newArray = [];
foreach ($array as $value) {
    if (str_contains($value, ['bot', 'BOT', 'Bot'])) {
        $newArray[] = $value;
    }
}

This will cycle through the array and use the laravel str_contains function to determine wether or not the array value has the word 'bot' or variants in it and then add it to a new array.

Comments

0

You can use laravel helper functions

$array = ['Mozilla', 'Mozilla', 'Mozillabot', 'Mozilla', 'Unicornbot'];    
$array = array_where($array, function($key, $value)
    {
        return str_contains($value, 'bot');
    });

Comments

0

You can use the array_where helper.

Along with the str_contains string helper like so

$array = ["Mozilla", "Mozilla", "Mozillabot", "Mozilla", "Unicornbot"];

$bots = array_where($array, function ($key, $value) {
    return str_contains(strtolower($value),array('bot'));
});

Or with the str_is string helper, which uses pattern matching, like this

$bots = array_where($array, function ($key, $value) {
    return str_is('*bot*',strtolower($value));
});

The check is done against lowercase strings to avoid variations on "Bot", "BOT" and so on.

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.