Reputation: 37
I am very close to solving the problem, however I can't figure out how to remove whitespaces that surround the string. Eg: ' ! '
, '! '
, and ' !'
become '!'
. And this applies to the ? character, . character and other punctuation characters.
Here is my code so far. It is supposed to take characters and convert them to nato words which I have done, but my punctuation is wrong. Eg ' ! awesome. .! '
turns to ' ! Alfa Whiskey Echo Sierra Oscar Mike Echo . . !'
when I dont want whitespaces between the punctuations.
function to_nato($words){
$key = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
$translationKey = array("Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "Xray", "Yankee", "Zulu");
$strToRet = "";
for($i = 0; $i < strlen($words); $i++) {
$letter = substr($words, $i, 1);
if(ctype_alpha($letter)) {
for($keySearch = 0; $keySearch < count($key); $keySearch++) {
$letterToSearch = array_search($key[$keySearch], $key);
if(strcasecmp($letter, $key[$letterToSearch]) == 0) {
$natoLetter = $translationKey[$letterToSearch];
$strToRet .= $natoLetter;
}
}
}
else {
$strToRet .= $letter;
}
}
$strToRet = preg_replace('/([a-z])([A-Z])/s','$1 $2', $strToRet);
//$strToRet = str_replace(" ! ", "!", $strToRet, $count);
return $strToRet;
}
Upvotes: 2
Views: 68
Reputation: 780929
Remove the spaces around punctuation from the original string:
$words = preg_replace('/\s*([^\w\s]+)\s*/', '$1', $words);
Upvotes: 0
Reputation: 4505
Try to change this if(ctype_alpha($letter)
to this if(ctype_alpha($letter) || $letter==" ")
. I could get rid of that space in the result (using the input string you provided in the description).
Upvotes: 1