0

I'm trying to do a generator of typographic ornaments that will produce something like "{(©+Φ+©)}" every time is called. I have some strings with the characters for each side of the ornament that I converted to arrays using str_split(). My problem is that they appear with the infamous question mark icon � and sometimes I get the error "Undefined offset". Am I missing something? maybe with the UTF-8 encoding? --Thanks for any hint!

function ornamento() {
  $izq = str_split("[{(]})");
  $der = str_split("]})[{(");
  $med = str_split("+÷×=#®©$%&?¿");
  $cen = str_split("ΔΘЖΣΤΥΦΧΨΩ");
  
  $idx1 = rand(1,sizeof($izq));
  $idx2 = rand(1,sizeof($izq));
  $mix1 = rand(1,sizeof($med));
  $mix2 = rand(1,sizeof($med));
  $cix  = rand(1,sizeof($cen));
  
  $ornamento = $izq[$idx1] . $izq[$idx2] . $med[$mix1] . $med[$mix2] .  $cen[$cix] . $med[$mix2] .  $med[$mix1] . $der[$idx2] . $der[$idx1];
  echo $ornamento;
  
}
holoman
  • 45
  • 8
  • 5
    `substr()` operates on byte offsets, and non-latin UTF8 characters use 2 or more bytes. Use [`mb_substr()`](https://www.php.net/manual/en/function.mb-substr) for this, and the equivalent `mb_*()` functions for other operations. https://www.php.net/manual/en/book.mbstring.php – Sammitch Aug 19 '21 at 20:42
  • 3
    See also: https://stackoverflow.com/questions/279170/utf-8-all-the-way-through – Sammitch Aug 19 '21 at 20:43

1 Answers1

0

The comment by @Sammitch worked perfectly. The function is now:

function ornamento() {
      $izq = "[{(]})";
      $der = "]})[{(";
      $med = "+÷×=#®©$%&**";
      $cen = "ΔΘЖΣΤΥΦΧΨΩ";
      
      $idx1 = rand(1,strlen($izq));
      $idx2 = rand(1,strlen($izq));
      $mix1 = rand(1,strlen($med));
      $mix2 = rand(1,strlen($med));
      $cix  = rand(1,strlen($cen));
      
      $ornamento = mb_substr($izq,$idx1,1) . mb_substr($izq,$idx2,1) . mb_substr($med,$mix1,1) . mb_substr($med,$mix2,1) .  mb_substr($cen,$cix,1) . 
                   mb_substr($med,$mix2,1) . mb_substr($med,$mix1,1) . mb_substr($der,$idx2,1) . mb_substr($der,$idx1,1);
      return $ornamento;
      
    }
holoman
  • 45
  • 8