Reputation: 96
Using PHP, how do you convert a string of decimal numbers with spaces in between into a string without spaces? (unless of course it is a DEC space (32) converted)
Example: 84 104 97 110 107 32 121 111 117
I have checked out the related questions and most of them are just asking what the built in function is for converting decimal to ascii. I know chr() and ord() and I think the solution really should use explode() and implode() along with a string replace. I am just horrible at for and foreach loops so the logic breaks my mind. :)
The closest SO topic I found is this one which is basically the opposite of what I am asking for - Using PHP to Convert ASCII Character to Decimal Equivalent
Upvotes: 0
Views: 1382
Reputation: 13283
This would be a situation where the strtok
function actually could be used for something.
The strtok
function tokenizes a string based on a character. In this case the token delimiter is a space. Each time you call strtok
it returns the next token in the string.
The chr
function is used to convert the ordinal (decimal) number to its ASCII character equivalent.
function myParseString($str) {
$output = ''; // What we will return
$token = strtok($str, ' '); // Initialize the tokenizer
// Loop until there are no more tokens left
while ($token !== false) {
$output .= chr($token); // Add the token to the output
$token = strtok(' '); // Advance the tokenizer, getting the next token
}
// All the tokens have been consumed, return the result!
return $output;
}
$str = '84 104 97 110 107 32 121 111 117';
echo myParseString($str);
(And you are welcome.)
Upvotes: 1