Skip to content

Instantly share code, notes, and snippets.

@fntneves
Last active September 9, 2016 10:22
Show Gist options
  • Save fntneves/7fb3c60ee7a65fc799eebbd2101c56e9 to your computer and use it in GitHub Desktop.
Save fntneves/7fb3c60ee7a65fc799eebbd2101c56e9 to your computer and use it in GitHub Desktop.
[Laravel] Support method to convert a given string to a searchable string (ascii+lowercase), according to the given minimum length.
<?php
namespace App\Support;
class Str extends \Illuminate\Support\Str
{
/**
* Returns the searchable string.
*
* @param string $string String to convert
* @param bool $replace Replace spaces
* @param int $min Minimum length of searchable string
* @param string $replaceWith Replace spaces with given string
* @return string $string
*/
public static function searchable($string, $replace = false, $min = 3, $replaceWith = '%')
{
// Remove duplicated spaces
$string = preg_replace('/\s+/', ' ', self::lower(self::ascii(trim($string))));
$splitString = explode(' ', $string);
$terms = array_filter($splitString, function($term) use ($min) {
return strlen($term) >= $min;
});
// There are terms that respect the minimum length, concatenate them and use it as search string.
if(count($terms) > 0) {
return implode($replace ? $replaceWith : ' ', $terms);
}
return $string;
}
}
@fntneves
Copy link
Author

fntneves commented Sep 9, 2016

Examples (with default parameters):

'wõrd' => 'word'
'a string' => 'string'
'search string' => 'search string' 
'   a    spaced    string  ' => 'spaced string' // filter terms with length < $min
'a  a' => 'a a' // there are no terms with length >= $min
...

When $replace = true;, spaces are replaced with $replaceWith.

'search string' => 'search%string'
'   a    spaced    string  ' => 'spaced%string' // filter terms with length < $min
'a a' => 'a a' // there are no terms with length >= $min, do not replace
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment