I tried Googling this but not sure what's the best thing to look for. What I am trying to do is to translate a text input to output the letters of a touch tone phone. For example Hello World would output 43550 96153the idea is I'm trying to use the tropo voice api system and want the user to be able to enter their name as touch tone values and match that to their name as numbers in my database.
I'm assuming this can be done with a function along the lines of
$input= $touchtone_value;
$number_two_array (a,b,c);
if( $input==in_array($number_two_array)){
$output = '2';
}
I'm sure this will work. However, if there is a class out there or a simpler function than to break each letter into number arrays I think that would be a better way to do it. At this point this is a fairly open ended question as I have NO IDEA where to start as the best way to accomplish this.
EDIT: I found a solution, not sure it's the best one.
$input = strtolower('HELLO WORLD');
echo 'input: '. $input. "\n";
echo $output = 'output: '. strtr($input,'abcdefghijklmnopqrstuvwxyz', '22233344455566677778889999');
input:hello world
output: 43556 96753
Now I just need to find a way to remove white space :)
http://codepad.org/Ieug0Zuw
Source: code a number into letters
PHP provides a function called strtr which does string translations. The first argument is what you want to translate, the second is the original characters, the third is the replacement characters. Below is a function that should do what you want. Edit: Updated my sample to strip out any characters that aren't supported (anything other than a-z or a space)
<?php
function get_tones($inp) {
$from = 'abcdefghijklmnopqrstuvwxyz ';
$to = '222333444555666777788899990';
// convert the input to lower case
$inp = strtolower($inp);
// remove anything that isn't a letter or a space
$inp = preg_replace('/[^a-z ]/', '', $inp);
return strtr($inp, $from, $to);
}
assert(get_tones('Hello world') == '43556096753');
assert(get_tones('Hell234"*&o world') == '43556096753');
assert(get_tones('ALEX') == '2539');
assert(get_tones(' ') == '0000');
How about a structure like this... NOTE: This will ignore invalid 'letters' like spaces, punctuation, etc..
LIVE DEMO http://codepad.org/pQHGhm7Y
<?php
echo getNumbersFromText('Hello There').'<br />';
echo getNumbersFromText('This is a really long text string').'<br />';
function getNumbersFromText($inp){
$result=array();
$inp = strtolower($inp);
$keypad = array('a' => '2', 'b' => '2', 'c' => '2', 'd' => '3',
'e' => '3', 'f' => '3', 'g' => '4', 'h' => '4',
'i' => '4', 'j' => '5', 'k' => '5', 'l' => '5',
'm' => '6', 'n' => '6', 'o' => '6', 'p' => '7',
'q' => '7', 'r' => '7', 's' => '7', 't' => '8',
'u' => '8', 'v' => '8', 'w' => '9', 'x' => '9',
'y' => '9', 'z' => '9');
for ($x=0; $x<strlen($inp); $x++){
$letter = $inp[$x];
if ($keypad[$letter]) $result[]= $keypad[$letter];
}
return implode('',$result);
}
?>
I'm not sure I understand exactly what you are asking:
Your input is words, and you want to output the corresponding numbers?
Your input is numbers, and you want to output the corresponding words?
In case (1), it's simple, just use an array that maps each letter of the alphabet to the corresponding numbers (i.e. key is letter, value is number). You can then just iterate over the characters of the input, and output using the corresponding element in the array.
Case (2) is a bit trickier. You can build a Trie from your list of names, and use it to do the lookup.
Related
Please help me to solve this issue. I'm not sure is it possible or not! I need a small tricky solution.
<?php include_once"system/hijri_calendar.php";
echo (new hijri\datetime()) -> format ('_j');
?>
Above code gives me an output of integer (1...30) in English.
Now, After echo, I want to change this English language to other languages.
Example:
Say Above code gives me an output 1
I want to change this output (1) to other languages (১)
If I get you right you are trying to get the value from one array based on the value and key from another array. You can use array_search() to find the key from array based on value
<?php
$en = array(1,2,3,4,5,6,7,8,9,0);
$bn = array('১','২','৩','৪','৫','৬','৭','৮','৯','০');
var_dump(array_search(5, $en)); // gives the key 4 from $en where value is 5
// array keys strart with 0
// so you can do
var_dump($bn[array_search(5, $en)]); // gives ৬
PHPFiddle to play with
Quick and dirty:
function __($number, $lang)
{
if ($lang == 'en') {
return $number;
}
$translate = array();
$translate['bn'] = array(
'1' => '১',
'2' => '২',
'3' => '৩',
'4' => '৪',
'5' => '৫',
'6' => '৬',
'7' => '৭',
'8' => '৮',
'9' => '৯',
'0' => '০'
);
$translate['th'] = array(
'1' => '๑',
'2' => '๒',
'3' => '๓',
'4' => '๔',
'5' => '๕',
'6' => '๖',
'7' => '๗',
'8' => '๘',
'9' => '๙',
'0' => '๐'
);
$digits = str_split($number,1);
$return_this = '';
foreach($digits as $digit){
$return_this .= $translate[$lang][$digit];
}
return $return_this;
}
echo __('905','bn');
Break down, if the lang is en you get what you give, if bn or th, it'll break the number apart and rebuild it using the requested array.
This is basically how I do I18n except the arrays for each language are in their own files.
I've changed the arrays slightly to simplify things. If the array is in the order of the digits (so I've moved the 0 element to position 0 in the array) you can use...
$bn = array('০','১','২','৩','৪','৫','৬','৭','৮','৯');
$in = "18";
$out = "";
foreach ( str_split($in) as $ch ) {
$out .= $bn[$ch];
}
echo $out;
I'm trying to get a random array for specific key.
this is my code so far,
$convert = array(
'a' => 'Amusing','Amazing',
'b' => 'Beyond',
'c' => 'Clever','Colorful','Calm',
'd' => 'Dangerous','Donkey',
'e' => 'Endangered',
'f' => 'Fancy',
'g' => 'Great',
'h' => 'Helpful','Humorous',
);
$txt="baca";
$txt=strtolower($txt);
$arr=str_split($txt);
foreach ($arr as $alfa) {
echo $alfa." = ".$convert[$alfa]."\n";
}
the output would be :
b = Beyond
a = Amusing
c = Clever
a = Amusing
but I'm trying to get
b = Beyond
a = Amusing
c = Clever
a = Amazing
Unique value for specific array ('a') in this case.
I tried to use array_rand but failed. I would appreciate any advice given..
This:
array(
'a' => 'Amusing','Amazing',
...
)
is equivalent to:
array(
'a' => 'Amusing',
0 => 'Amazing',
...
)
You're not specifying a key for the word "Amazing", so it automatically gets a numeric key. It does not in any way actually belong to the 'a' key, even if you write it on the same line.
What you want is:
array(
'a' => array('Amusing', 'Amazing'),
...
)
And then:
$values = $convert['a'];
echo $values[array_rand($values)];
Sometime back I was getting alot of data via some API and I saved it into a flat file doing a simple var_dump or print_r. Now I am looking to process the data and each line looks like:
" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y',
'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name'
=> 'MNOP', 'email' => 'abc#example.com', 'city' => 'London',
'street_address' => 'Sample', 'first_name' => 'Sparsh',"
Now I need to get this data back into an array format. Is there a way I can do that?
What about first exploding the string with the explode() function, using ', ' as a separator :
$str = "'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',";
$items = explode(', ', $str);
var_dump($items);
Which would get you an array looking like this :
array
0 => string ''middle_initial' => ''' (length=22)
1 => string ''sid' => '1419843'' (length=18)
2 => string ''fixed' => 'Y'' (length=14)
3 => string ''cart_weight' => '0'' (length=20)
...
And, then, iterate over that list, matching for each item each side of the =>, and using the first side of => as the key of your resulting data, and the second as the value :
$result = array();
foreach ($items as $item) {
if (preg_match("/'(.*?)' => '(.*?)'/", $item, $matches)) {
$result[ $matches[1] ] = $matches[2];
}
}
var_dump($result);
Which would get you :
array
'middle_initial' => string '' (length=0)
'sid' => string '1419843' (length=7)
'fixed' => string 'Y' (length=1)
'cart_weight' => string '0' (length=1)
...
But, seriously, you should not store data in such an awful format : print_r() is made to display data, for debugging purposes -- not to store it an re-load it later !
If you want to store data to a text file, use serialize() or json_encode(), which can both be restored using unserialize() or json_decode(), respectively.
Although I wholeheartedly agree with Pascal Martin, if you have this kind of data to deal with, the following (as Pascal's first suggestion mentions) could work depending on your actual content. However, do yourself a favor and store your data in a format that can be reliably put back into a PHP array (serialize, JSON, CSV, etc...).
<pre>
<?php
$str = "\" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',\"";
function myStringToArray($str) {
$str = substr($str, 1, strlen(substr($str, 0, strlen($str)-2)));
$str = str_replace("'",'',$str);
$strs = explode(',', $str);
$arr = array();
$c_strs = count($strs);
for ($i = 0; $i < $c_strs; $i++) {
if (strpos($strs[$i],'=>') !== false) {
$_arr = explode('=>',$strs[$i]);
$arr[trim($_arr[0])] = trim($_arr[1]);
}
}
return $arr;
}
print_r(myStringToArray($str));
?>
</pre>
http://jfcoder.com/test/substr.php
Note, you would need to adjust the function if you have comma's within your array member's content (for instance, using Pascal's suggestion about the ', ' token).
It would be better and much easier to work with Serialize and Unserialize instead of var_dump.
in that form, maybe you could try a
explode(' => ', $string)
and then go through the array and put the pairs together in a new array.
As long as it's the output of print_r and an array, you can use my little print_r converter, PHP source code is available with the link.
The tokenizer is based on regular expressions so you can adopt it to your needs. The parser deals with forming the PHP array value.
You will find the latest version linked on my profile page.
Right to the problem...user need to input text (to be specific the input text is serial number), this input must be compared with database. However because of small print user will make mistake between characters like: (B/8), (1/l),(0,o),(u,v).
The question is how to make the user input "l234B" a valid entry when the serial number is "12348"??
here is another examples: o12u3 ---> 012v3
thanks.
Some solution might be to replace all occorences like "8" by "[8B]" to match against both possibilities:
$sn = "l234B"; $sn_new = "";
$problematic_chars = ['B' => 'B8', '8' => 'B8', '1' => '1l', 'l' => '1l', ...];
// Go through original string and create new string
// "l234B" becomes "[1l]234[8B]"
for($i = 0; $i < strlen($sn); $i++) {
$char = $sn[$i];
if (array_key_exists($char, $problematic_chars)) {
$sn_new .= "[".$problematic_chars[$char]."]";
} else {
$sn_new .= $char;
}
}
// Query stuff
$sql = "SELECT * FROM table_name WHERE sn REGEXP '^${sn_new}\$'";
Did not write PHP for long time, but I think you get the idea.
You may want to try similar_text function rather than using regular expressions and validate only non-ambiguous chars.
// to query
$id = "ABF8...";
// all combinations pre-generated
$c = array(
array('B' => 'B', '8' => '8', ...),
array('B' => 'B', '8' => 'B', ...),
array('B' => '8', '8' => '8', ...),
array('B' => '8', '8' => 'B', ...),
...
);
// generating all versions
foreach($c as $v)
{
$ids[] = strtr($id, $v);
}
the optimal solution depends on your specific setup. but probably you will have the IDs somewhere and you have to query them. so you will have to replace the ambigiuous chars in all possible combinations and query those.
strtr()
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Converting words to numbers in PHP
I need a function to convert textual numbers to numbers.
For example: convert("nine") outputs 9
I know I could write a function like for example if ($number == "one") { $number = 1; } etc...
but that would be a lot of work.
Use the switch statement.
Use a lookup table like this:
$numbers = array(
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9
);
$digit = strtolower($digit);
if (isset($numbers[$digit])) {
$digit = $numbers[$digit];
}
Note I use strtolower just in case. Of course, this solution would be impractical for anything over a couple dozen. Beyond that, you'll need some sort of parser.