Search code examples
phparraysstringtrim

I want to add symbol at random place in string how can i do that?


$string = "this is a string biggest string bigger than the string1 string";   
$random_position = rand(0, strlen($string) - 1);
$chars = "πŸ‘΄πŸΏπŸ‘©πŸΏβ€πŸ’»πŸ§‘πŸΏβ€πŸš€πŸ§šπŸΏπŸ€¦πŸΏβ€β™€οΈπŸ‘¬πŸΏπŸš£πŸΏβ€β™‚οΈβœ‘οΈβ™ˆοΈπŸˆ―οΈπŸ†—πŸ‘©πŸΎβ€β€οΈβ€πŸ‘©πŸΌπŸ§‘πŸΌβ€β€οΈβ€πŸ§‘πŸ»";
$random_char = $chars[rand(0, strlen($chars) - 1)];
$newString = substr($string, 0, $random_position) . $random_char . substr($string, $random_position);
echo $newString;

this is my code and I want to add these symbols in my string at random places but I can't do it. does anyone can help me??


Solution

  • The problem is that your $chars string has multibyte characters, so when you address $chars[$i] for some $i, you'll just get one part of a multibyte character, not in full.

    The solution is to use mb_ functions:

    $chars = mb_str_split("πŸ‘΄πŸΏπŸ‘©πŸΏβ€πŸ’»πŸ§‘πŸΏβ€πŸš€πŸ§šπŸΏπŸ€¦πŸΏβ€β™€οΈπŸ‘¬πŸΏπŸš£πŸΏβ€β™‚οΈβœ‘οΈβ™ˆοΈπŸˆ―οΈπŸ†—πŸ‘©πŸΎβ€β€οΈβ€πŸ‘©πŸΌπŸ§‘πŸΌβ€β€οΈβ€πŸ§‘πŸ»");
    $random_char = $chars[rand(0, count($chars) - 1)];
    

    With this it will work.