Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading