Php one two three

Converting a number (1, 2, 3) to a string (one, two, three) in PHP

Here’s one I wrote way back in college. It includes support for negative numbers, as well. I know there’s some ways it could be shortened and/or cleaned up, but hey, it works well for any integer!

/** Converts an integer to its textual representation. @param num the number to convert to a textual representation @param depth the number of times this has been recursed */ function readNumber($num, $depth=0) < $num = (int)$num; $retval =""; if ($num < 0) // if it's any other negative, just flip it and call again return "negative " + readNumber(-$num, 0); if ($num >99) // 100 and above < if ($num >999) // 1000 and higher $retval .= readNumber($num/1000, $depth+3); $num %= 1000; // now we just need the last three digits if ($num > 99) // as long as the first digit is not zero $retval .= readNumber($num/100, 2)." hundred\n"; $retval .=readNumber($num%100, 1); // our last two digits > else // from 0 to 99 < $mod = floor($num / 10); if ($mod == 0) // ones place < if ($num == 1) $retval.="one"; else if ($num == 2) $retval.="two"; else if ($num == 3) $retval.="three"; else if ($num == 4) $retval.="four"; else if ($num == 5) $retval.="five"; else if ($num == 6) $retval.="six"; else if ($num == 7) $retval.="seven"; else if ($num == 8) $retval.="eight"; else if ($num == 9) $retval.="nine"; >else if ($mod == 1) // if there's a one in the ten's place < if ($num == 10) $retval.="ten"; else if ($num == 11) $retval.="eleven"; else if ($num == 12) $retval.="twelve"; else if ($num == 13) $retval.="thirteen"; else if ($num == 14) $retval.="fourteen"; else if ($num == 15) $retval.="fifteen"; else if ($num == 16) $retval.="sixteen"; else if ($num == 17) $retval.="seventeen"; else if ($num == 18) $retval.="eighteen"; else if ($num == 19) $retval.="nineteen"; >else // if there's a different number in the ten's place < if ($mod == 2) $retval.="twenty "; else if ($mod == 3) $retval.="thirty "; else if ($mod == 4) $retval.="forty "; else if ($mod == 5) $retval.="fifty "; else if ($mod == 6) $retval.="sixty "; else if ($mod == 7) $retval.="seventy "; else if ($mod == 8) $retval.="eighty "; else if ($mod == 9) $retval.="ninety "; if (($num % 10) != 0) < $retval = rtrim($retval); //get rid of space at end $retval .= "-"; >$retval.=readNumber($num % 10, 0); > > if ($num != 0) < if ($depth == 3) $retval.=" thousand\n"; else if ($depth == 6) $retval.=" million\n"; if ($depth == 9) $retval.=" billion\n"; >return $retval; > 

Not really ideal, but atleast better than a ‘huge switch statement’:

 $numbermappings = array("zero", "one","two","three", "four" . "ninetynine"); echo $numbermappings[4]; // four 

You still have to write that huge array though..

Читайте также:  Document body style css

pear has a package Numbers_Words:

$numberToWord = new Numbers_Words(); echo $numberToWords->toWords(200);

****See this function in action:****

function N2L($number) < $result = array(); $tens = floor($number / 10); $units = $number % 10; $words = array ( 'units' =>array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'), 'tens' => array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety') ); if ($tens < 2) < $result[] = $words['units'][$tens * 10 + $units]; >else < $result[] = $words['tens'][$tens]; if ($units >0) < $result[count($result) - 1] .= '-' . $words['units'][$units]; >> if (empty($result[0])) < $result[0] = 'Zero'; >return trim(implode(' ', $result)); > 

Источник

Converting a Number (1, 2, 3) to a String (One, Two, Three) in PHP

Converting a number (1, 2, 3) to a string (one, two, three) in PHP

pear has a package Numbers_Words:

$numberToWord = new Numbers_Words();
echo $numberToWords->toWords(200);

convert number(1,2,3) to string(one,two,three) Cake PHP

$num = 4263;

$numbers10 = array('ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');
$numbers01 = array('one','two','three','four','fife','six','seven','eight','nine','ten',
'eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen');

if($num == 0) echo "zero";
>

$thousands = floor($num/1000);
if($thousands != 0) echo $numbers01[$thousands-1] . " thousand ";
$num -= $thousands*1000;
>

$hundreds = floor($num/100);
if($hundreds != 0) echo $numbers01[$hundreds-1] . " hundred ";
$num -= $hundreds*100;
>

if($num < 20) if($num != 0) echo $numbers01[$num-1];
>
> else $tens = floor($num/10);
echo $numbers10[$tens-1] . " ";
$num -= $tens*10;

if($num != 0) echo $numbers01[$num-1];
>
>

four thousand two hundred sixty three

PHP increase word (one — two — three)

There is an example in this documentation.

 function int_to_words($x) global $nwords;

if(!is_numeric($x))
$w = '#';
else if(fmod($x, 1) != 0)
$w = '#';
else if($x < 0) $w = 'minus ';
$x = -$x;
> else
$w = '';
// . now $x is a non-negative integer.

if($x < 21) // 0 to 20
$w .= $nwords[$x];
else if($x < 100) < // 21 to 99
$w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
$w .= '-'. $nwords[$r];
> else if($x < 1000) < // 100 to 999
$w .= $nwords[floor($x/100)] .' hundred';
$r = fmod($x, 100);
if($r > 0)
$w .= ' and '. int_to_words($r);
> else if($x < 1000000) < // 1000 to 999999
$w .= int_to_words(floor($x/1000)) .' thousand';
$r = fmod($x, 1000);
if($r > 0) $w .= ' ';
if($r < 100)
$w .= 'and ';
$w .= int_to_words($r);
>
> else < // millions
$w .= int_to_words(floor($x/1000000)) .' million';
$r = fmod($x, 1000000);
if($r > 0) $w .= ' ';
if($r < 100)
$word .= 'and ';
$w .= int_to_words($r);
>
>
>
return $w;
>

Number to String Value in php

$cypher = array('zero','one','two','three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
$i = 9;
echo $cypher[$i];

PHP: increment counter function using words (i.e. First, Second, Third, etc.. )

There is a class from PEAR package can do that:


// include class
include("Numbers/Words.php");

// create object
$nw = new Numbers_Words();

// convert to string
echo "600 in words is " . $nw->toWords(600);

?>

Convert a number to its string representation

for the first option (spell out digits), strtr is your friend

$words = array( 
'-' => 'minus ',
'1' => 'one ',
'2' => 'two ',
etc.
);

echo strtr(-123, $words);

How to convert number into word

function createFullWordOrdinal($number)
$ord1 = array(1 => "first", 2 => "second", 3 => "third", 5 => "fifth", 8 => "eight", 9 => "ninth", 11 => "eleventh", 12 => "twelfth", 13 => "thirteenth", 14 => "fourteenth", 15 => "fifteenth", 16 => "sixteenth", 17 => "seventeenth", 18 => "eighteenth", 19 => "nineteenth");
$num1 = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen");
$num10 = array("zero", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety");
$places = array(2 => "hundred", 3 => "thousand", 6 => "million", 9 => "billion", 12 => "trillion", 15 => "quadrillion", 18 => "quintillion", 21 => "sextillion", 24 => "septillion", 27 => "octillion");

$number = array_reverse(str_split($number));

if ($number[0] == 0)
if ($number[1] >= 2)
$out = str_replace("y", "ieth", $num10[$number[1]]);
else
$out = $num10[$number[1]]."th";
>
else if (isset($number[1]) && $number[1] == 1)
$out = $ord1[$number[1] . $number[0]];
>
else
if (array_key_exists($number[0], $ord1))
$out = $ord1[$number[0]];
else
$out = $num1[$number[0]]."th";
>

if((isset($number[0]) && $number[0] == 0) || (isset($number[1]) && $number[1] == 1))
$i = 2;
>
else
$i = 1;
>

while ($i < count($number))
if ($i == 1)
$out = $num10[$number[$i]] . " " . $out;
$i++;
>
else if ($i == 2)
$out = $num1[$number[$i]] . " hundred " . $out;
$i++;
>
else
if (isset($number[$i + 2]))
$tmp = $num1[$number[$i + 2]] . " hundred ";
$tmpnum = $number[$i + 1].$number[$i];
if ($tmpnum < 20)
$tmp .= $num1[$tmpnum] . " " . $places[$i] . " ";
else
$tmp .= $num10[$number[$i + 1]] . " " . $num1[$number[$i]] . " " . $places[$i] . " ";

$out = $tmp . $out;
$i+=3;
>
else if (isset($number[$i + 1]))
$tmpnum = $number[$i + 1].$number[$i];
if ($tmpnum < 20)
$out = $num1[$tmpnum] . " " . $places[$i] . " " . $out;
else
$out = $num10[$number[$i + 1]] . " " . $num1[$number[$i]] . " " . $places[$i] . " " . $out;
$i+=2;
>
else
$out = $num1[$number[$i]] . " " . $places[$i] . " " . $out;
$i++;
>
>
>
return $out;
>

This will give you the output you want.

createFullWordOrdinal(1) ----> first
createFullWordOrdinal(2) ----> second
createFullWordOrdinal(3) ----> third
createFullWordOrdinal(4) ----> fourth

Is there an easy way to convert a number to a word in PHP?

I found some (2007/2008) source-code online and as it is copyright but I can use it freely and modify it however I want, so I place it here and re-license under CC-Wiki:

/** 
* English Number Converter - Collection of PHP functions to convert a number
* into English text.
*
* This exact code is licensed under CC-Wiki on Stackoverflow.
* http://creativecommons.org/licenses/by-sa/3.0/
*
* @link http://stackoverflow.com/q/277569/367456
* @question Is there an easy way to convert a number to a word in PHP?
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
* You can use this freely and modify it however you want.
*/

function convertNumber($number)
list($integer, $fraction) = explode(".", (string) $number);

$output = "";

if ($integer == "-")
$output = "negative ";
$integer = ltrim($integer, "-");
>
else if ($integer == "+")
$output = "positive ";
$integer = ltrim($integer, "+");
>

if ($integer == "0")
$output .= "zero";
>
else
$integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
$group = rtrim(chunk_split($integer, 3, " "), " ");
$groups = explode(" ", $group);

$groups2 = array();
foreach ($groups as $g)
$groups2[] = convertThreeDigit($g, $g, $g);
>

for ($z = 0; $z < count($groups2); $z++)
if ($groups2[$z] != "")
$output .= $groups2[$z] . convertGroup(11 - $z) . (
$z < 11
&& !array_search('', array_slice($groups2, $z + 1, -1))
&& $groups2[11] != ''
&& $groups[11] == '0'
? " and "
: ", "
);
>
>

$output = rtrim($output, ", ");
>

if ($fraction > 0)
$output .= " point";
for ($i = 0; $i < strlen($fraction); $i++)
$output .= " " . convertDigit($fraction);
>
>

return $output;
>

function convertGroup($index)
switch ($index)
case 11:
return " decillion";
case 10:
return " nonillion";
case 9:
return " octillion";
case 8:
return " septillion";
case 7:
return " sextillion";
case 6:
return " quintrillion";
case 5:
return " quadrillion";
case 4:
return " trillion";
case 3:
return " billion";
case 2:
return " million";
case 1:
return " thousand";
case 0:
return "";
>
>

function convertThreeDigit($digit1, $digit2, $digit3)
$buffer = "";

if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0")
return "";
>

if ($digit1 != "0")
$buffer .= convertDigit($digit1) . " hundred";
if ($digit2 != "0" || $digit3 != "0")
$buffer .= " and ";
>
>

if ($digit2 != "0")
$buffer .= convertTwoDigit($digit2, $digit3);
>
else if ($digit3 != "0")
$buffer .= convertDigit($digit3);
>

return $buffer;
>

function convertTwoDigit($digit1, $digit2)
if ($digit2 == "0")
switch ($digit1)
case "1":
return "ten";
case "2":
return "twenty";
case "3":
return "thirty";
case "4":
return "forty";
case "5":
return "fifty";
case "6":
return "sixty";
case "7":
return "seventy";
case "8":
return "eighty";
case "9":
return "ninety";
>
> else if ($digit1 == "1")
switch ($digit2)
case "1":
return "eleven";
case "2":
return "twelve";
case "3":
return "thirteen";
case "4":
return "fourteen";
case "5":
return "fifteen";
case "6":
return "sixteen";
case "7":
return "seventeen";
case "8":
return "eighteen";
case "9":
return "nineteen";
>
> else
$temp = convertDigit($digit2);
switch ($digit1)
case "2":
return "twenty-$temp";
case "3":
return "thirty-$temp";
case "4":
return "forty-$temp";
case "5":
return "fifty-$temp";
case "6":
return "sixty-$temp";
case "7":
return "seventy-$temp";
case "8":
return "eighty-$temp";
case "9":
return "ninety-$temp";
>
>
>

function convertDigit($digit)
switch ($digit)
case "0":
return "zero";
case "1":
return "one";
case "2":
return "two";
case "3":
return "three";
case "4":
return "four";
case "5":
return "five";
case "6":
return "six";
case "7":
return "seven";
case "8":
return "eight";
case "9":
return "nine";
>
>

Источник

Кастуем магией PHP

PHP замечательный язык программирования. При всех его недостатках он не перестает удивлять. Недавно столкнулся со следующим — на первый взгляд загадочным — его поведением.

Как известно PHP имеет встроенный шаблонизатор. Весь текст, который интерпретатор встречает между тегами обозначающими конец и начало PHP кода, он отправляет в буфер вывода. Убедиться в этом можно на следующем примере:

Выводом программы будет «Hello, World. All is fine», что и следовало ожидать. Но что происходит на самом деле? Посмотрим на другой пример:

 Three ; $one = function() < ?>One ; $two = function() < ?>Two ; $one(); $two(); $three(); 

Если выполнить исходный код, то выводом программы будет «One Two Three», что немного странно. Ведь текст в коде встречался совсем в другой последовательности и в буфер вывода должно было попасть «Three One Two».

На самом деле PHP не отправляет текст в буфер вывода как только он его встречает. В интерпретаторе языка есть специальный опкод ZEND_ECHO (в этот опкод транслируется echo) и кусок текста между PHP кодом будут транслироваться в аргумент этого опкода. Именно поэтому у нас текст во втором примере выводиться в той последовательности в которой мы вызываем созданные анонимные функции (вывод текста стал частью анонимных функций благодаря опкоду ZEND_ECHO.

В подтверждении моих слов кусочек содержимого файла zend_language_parser.y

И реализация самой функции zend_do_echo из zend_compile.c:

void zend_do_echo(const znode *arg TSRMLS_DC) /* opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); > /* >>> */ 
Ну и какой от этого толк?

Толк на самом деле есть. Ведь мы можем привязать к анонимной функции произвольный вывод, а значит теоретически это можно использовать в реализации шаблонизатора. Немного подумав я набросал следующий вариант содержимого файла такого теоретического шаблонизатора:

    li->addClassIf(1, ‘active’)->setContent(‘Main’) ;?>li->addClassIf(0, ‘active’)->setContent(‘Account’) ;?>li->addClassIf(0, ‘active’)->setContent(‘FAQ’) ;?>li->addClassIf(0, ‘active’)->setContent(‘Logout’) ;?>

Где в переменой $c->header объект класса CElement. Удобно? На вкус и цвет товарищей нет)

P.S.
Из официальной документации поведение интерпретатора не совсем очевидно. Более того в ней совсем не упоминается о преобразовании текста в аргумент опкода: when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline — see instruction separation) until it hits another opening tag

Источник

Оцените статью