Tanuj1899
Tanuj1899

Reputation: 53

Capitalize random letters of a string in PHP

I want to capitalize random letters in a string and echo the complete sentence from hello69.world to HeLlO69.WoRlD. Each time the functions run, it should capitalize random letters and exclude special characters and digits. I've tried this so far but it only selects the first 5 characters in string every time and outputs only Capitalized letters. How to fix this?

<?php
 $string = "hellohg.09ui8vkosjbdh";

    $selchr = substr($string,0, 5);
    $caps = strtoupper($selchr);
    echo substr_replace($string, $caps,0);
?>

Upvotes: 0

Views: 1093

Answers (1)

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9263

Let's assume you want to CAPITALIZE 5 letters randomly:

$string = "hellohg.09ui8vkosjbdh";
$characters = str_split($string);
$i = 0;
do{
    $random_index = rand(0, count($characters) - 1);
    $unique_indices[] = ""; //UNIQUE INDICES
    while (in_array($random_index, $unique_indices)) {
        $random_index = rand(0, count($characters) - 1);
    }
    $unique_indices[] = $random_index;

    $random_letter = $characters[$random_index];
    if(ctype_alpha($random_letter)){//only letters 
        $characters[$random_index] = strtoupper($random_letter);
        $i++;
    }
}while($i<5);echo implode('', $characters);

Thanks to @El_Vanja for Note UNIQUE INDICES

Upvotes: 1

Related Questions