0

I am using this to create username based on name. Name needs to be utf8 but username does not. How could I convert utf8 to non utf8?

public static function createUsername ($name, $count = 0) {
        $username = implode('.', explode(' ', strtolower($name)));

        if ($count > 0) {
            $username = $username . $count;
        }

        if (count(self::where('username', $username)->get()) > 0) {
            self::createUsername($name, $count++);
        }

        return $username;
    }
Learner
  • 723
  • 3
  • 13
  • 36
  • You could try [utf8_decode()](https://www.php.net/manual/en/function.utf8-decode.php) or [iconv()](https://www.php.net/manual/en/function.iconv.php) – Alex Barker Sep 27 '19 at 20:45
  • First one returned ? instead of letter and second one error. – Learner Sep 27 '19 at 20:56

1 Answers1

3

Laravel provides a function for converting utf-8 strings into ASCCI.

Str::ascii($string)

I'm not entirely sure why you would want to do this as the performance gain is likely not all too great. See Does using ASCII/Latin Charset speed up the database?

jnadon
  • 126
  • 5
  • 1
    Well I got problem with nuxt and laravel encoding ut8 strings. Username is used by get method from url, so it makes so ugly string that doesn't work in laravel. I didn't want to go through nuxt crap since a lot of their things has problems. God kill me why I tried nuxt instead of react on angular.... – Learner Sep 27 '19 at 20:59
  • if you're planning on using the stringsas part of a query, I'd take a look at urlencode()/urldevcode() https://www.php.net/manual/en/function.urlencode.php https://www.php.net/manual/en/function.urldecode.php It may be what you're looking for instead. – jnadon Sep 27 '19 at 21:02