-1

I made a function that checks the similarity between strings. It works by splitting the input into separate words, and checking if the destination string contains that word. If it contains more than one, it is more similar. But not about that. Unfortunately, this doesn't work with characters like "Ą, Ł, Ś" and so on. For example, the word "URZAD" is not found in the string "URZĄD something something".

The function:

$suggestedProjects = collect($projects)
    ->map(function ($project) use ($wordsArray) {
    $project->similarity = count(array_filter($wordsArray, function ($word) use ($project) {
        return stripos($project->name, $word) !== false;
    }));
    return $project;
})
->filter(function ($entry) {
    return $entry->similarity > 0;
})
->sortByDesc('similarity')
->take(3)
->values();

A page where you can test and see what I'm talking about: https://laravelplayground.com/#/

Just paste that code and click "Run" in right bottom corner, or click Ctrl+Enter.

<?php
$projects = [(object)["id" => 333, "name" => "URZĄD something something"]];
$projectsWithoutĄ = [(object)["id" => 333, "name" => "URZAD something something"]];
$wordsArray = ['urząd'];
$wordsArrayWithoutĄ = ['urzad'];

/// WITH Ą
        $suggestedProjects = collect($projects)
            ->map(function ($project) use ($wordsArray) {
            $project->similarity = count(array_filter($wordsArray, function ($word) use ($project) {
                return stripos($project->name, $word) !== false;
            }));
            return $project;
        })
        ->filter(function ($entry) {
            return $entry->similarity > 0;
        })
        ->sortByDesc('similarity')
        ->take(3)
        ->values();

/// WITHOUT Ą
        $suggestedProjectsWithoutĄ = collect($projectsWithoutĄ)
            ->map(function ($project) use ($wordsArrayWithoutĄ) {
            $project->similarity = count(array_filter($wordsArrayWithoutĄ, function ($word) use ($project) {
                return stripos($project->name, $word) !== false;
            }));
            return $project;
        })
        ->filter(function ($entry) {
            return $entry->similarity > 0;
        })
        ->sortByDesc('similarity')
        ->take(3)
        ->values();


dump($suggestedProjects);
dump($suggestedProjectsWithoutĄ);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

0 Answers0