Skip to content

Commit

Permalink
feat: add str util toSearchablePhrases
Browse files Browse the repository at this point in the history
  • Loading branch information
kocoten1992 committed Nov 26, 2022
1 parent c1ffef7 commit 15e87c8
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 3 deletions.
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,8 @@
"psr-4": {
"Talmp\\Phputils\\": "src/"
}
},
"require": {
"voku/portable-ascii": "^2.0"
}
}
81 changes: 78 additions & 3 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 56 additions & 0 deletions src/StrUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,64 @@

namespace Talmp\Phputils;

use voku\helper\ASCII;

class StrUtil
{
public static function toSearchablePhrases(
string $string,
string $separator = ' ',
int $limit = PHP_INT_MAX,
int $min_length = 1,
): array {
$explode_arr = explode($separator, $string, $limit);

$result = [];

// in case input string is not ascii
// eg: léon
// and with min_length = 1
// we will split it into
// ['l', 'é', 'e', 'o', 'n', 'lé', 'le', 'éo', 'eo', 'on', 'léo', 'leo', 'éon', 'eon', 'léon', 'leon']

foreach ($explode_arr as $sub_string) {
$mb_str_split = mb_str_split($sub_string);

$sub_string_length = count($mb_str_split);
$pointer = 0;

while (true) {
if ($pointer > $sub_string_length - 1) {
break;
}

$length = 1;

while ($pointer + $length < $sub_string_length + 1) {
$result[implode('', array_slice($mb_str_split, $pointer, $length))] = true;
$result[static::ascii(implode('', array_slice($mb_str_split, $pointer, $length)))] = true;
$length += 1;
}

$pointer += 1;
}
}

return array_keys($result);
}

/**
* Transliterate a UTF-8 value to ASCII.
*
* @param string $value
* @param string $language
* @return string
*/
public static function ascii(string $value, string $language = 'en')
{
return ASCII::to_ascii($value, $language);
}

public static function replaceOnceIndex(
array $searches,
array $indexes,
Expand Down
7 changes: 7 additions & 0 deletions tests/StrUtilTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@

class StrUtilTest extends TestCase
{
public function test_to_searchable_phrases()
{
$this->assertEquals(16, count(StrUtil::toSearchablePhrases('léon')));

$this->assertEquals(32, count(StrUtil::toSearchablePhrases('amélie')));
}

public function test_replace_once()
{
// case 0
Expand Down

0 comments on commit 15e87c8

Please sign in to comment.