A PHP example to sort all words of a text in alphabetical order and write the words into a file.

<?php
function sort_all_words_and_write_into_file($text,$file){
    preg_match_all("/[a-z0-9_\-]+/i",$text,$matches,PREG_PATTERN_ORDER);
 
    $matches = array_unique($matches[0]);
 
    natcasesort($matches);
 
    $file_content = "";
 
    while(current($matches)){
        $file_content .= current($matches);
 
        if(next($matches)){
            $file_content .= "\r\n";
        }
    }
 
    if(file_exists($file)){
        if(is_writable($file)){
            if(file_put_contents($file,$file_content)){
                return true;
            }
        }
    }else{
        if(file_put_contents($file,$file_content)){
            return true;
        }
    }
 
    return false;
}
 
$text = "A PHP example to sort all words of a text in alphabetical order and write the words into a file.";
 
sort_all_words_and_write_into_file($text,"file.txt");
?>

The function returns false if the words haven’t been written into the file.

Share

Leave a Reply

Info