Tengo los siguientes tres casos en los que esperaría mostrar el mismo resultado, pero hace algo extraño para $str1
:
<?php $str1 = "— lorem lorem Alice lorem lorem lorem loremlorem"; // | < Why would a dash make a difference in the the found index? $str2 = "a lorem lorem Alice lorem lorem lorem loremlorem"; $str3 = " lorem lorem Alice lorem lorem lorem loremlorem"; // The found index is always the same $foundIndex = mb_stripos($str1, "Alice"); var_dump(substr($str1, $foundIndex - 6, 24), $foundIndex); $foundIndex = mb_stripos($str2, "Alice"); var_dump(substr($str2, $foundIndex - 6, 24), $foundIndex); $foundIndex = mb_stripos($str3, "Alice"); var_dump(substr($str3, $foundIndex - 6, 24), $foundIndex);
Salida :
string(24) "m lorem Alice lorem lore" << Why is this swapped to the right one char? int(14) string(24) "lorem Alice lorem lorem " int(14) string(24) "lorem Alice lorem lorem " int(14)
Puedes probarlo aquí .
Uso las operaciones mb_stripos
y substr
para buscar en cadenas y este es el PoC.
¿Por qué ocurre esto y cómo puedo corregir el comportamiento de las cadenas que contienen caracteres especiales?
A partir de una comprobación rápida —
creo que ocupa tres bytes, y substr
funciona por bytes, no por caracteres . strlen("—")
es 3
también...
¿Cómo puedo dividir la cadena por caracteres, en lugar de por bytes? Cortarlo por bytes realmente no funcionará para mí. Y todos los caracteres especiales deben manejarse correctamente. Si no me equivoco, los emojis también tienen diferentes tamaños.
El guión em que está utilizando es un carácter de varios bytes. Para realizar una operación substr() segura de varios bytes, debe usar mb_substr()
.
<?php $str1 = "— lorem lorem Alice lorem lorem lorem loremlorem"; // | < Why would a dash make a difference in the the found index? $str2 = "a lorem lorem Alice lorem lorem lorem loremlorem"; $str3 = " lorem lorem Alice lorem lorem lorem loremlorem"; // The found index is always the same $foundIndex = mb_stripos($str1, "Alice"); var_dump(mb_substr($str1, $foundIndex - 6, 24), $foundIndex); $foundIndex = mb_stripos($str2, "Alice"); var_dump(mb_substr($str2, $foundIndex - 6, 24), $foundIndex); $foundIndex = mb_stripos($str3, "Alice"); var_dump(mb_substr($str3, $foundIndex - 6, 24), $foundIndex);
Esta es la razón por:
echo strlen('-') . "\n"; // equals 1 using a normal dash echo strlen('—') . "\n"; // equals 3 using your "em dash"
Entonces, si haces echo substr($str1, 0, 3) . "\n";
obtienes tu "em dash".