Last active
September 9, 2016 10:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples (with default parameters):
When
$replace = true;
, spaces are replaced with$replaceWith
.