I want to write a function that take input as a string and convert alphabets to number and returns the converted numbers, in this way: A(a)=1, B(b)=2, C(c)=3... Z(z)=25 using php
thanks in advance
First, we make everything lowercase.
Then, using the ord function, we get the ascii code, and then substract 'a' from it.
function one_char_map($chr)
{
$chr=strtolower($chr);
return ord($chr)-ord('a');
}
function string_map($str)
{
return implode(array_map('one_char_map',str_split($str)));
}
echo string_map('abcD');//0123
Please try this :
function conv($alph=null){
return (!is_null($alph)?strpos("abcdefghijklmnopqrstuvwxyz", $alph):"Need String");
}
echo "<br /><br />";
echo conv("a");
EDIT :
$str = "abcDefghZ";
$out = "";
for($i=0;$i<strlen($str);$i++){
$out .= conv(strtolower($str[$i]));
}
echo $str."<br />".$out;
If you trying to roll your own hash function: DONT.
If you need to accept other characters from ASCII, use PHP's ord() function.
Try this:
This function returns the position, and optionally accepts a base integer to shift the numbers if you need to.
function alpha_ord($str, $base = 0) {
$pos = stripos(
'abcdefghijklmnopqrstuvwxyz',
$str{0}
);
if ($pos !== FALSE) {
$pos += $base;
}
return $pos;
}
print alpha_ord('A'); // 0
print alpha_ord('Z', 1); // 26
print alpha_ord('Z'); // 25
print alpha_ord('A', 65); // 65
I'm trying to write a php function that will grab the first letter from a long string ("ZT-FUL-ULT-10SF-S" would return "Z").
Some of the strings start with numbers, and for those, the function needs to return "#".
function returnFirst($rsrnum) {
substr("$rsrnum", 0, 1); {
echo "$rsrnum";
}
}
That's as far as I've gotten. How would I differentiate between numbers, and if it is a number, return #?
Thanks!
Edit: Seems to be working like a champ with:
function returnFirst($rsrnum) {
$char = substr($rsrnum, 0, 1);
return ctype_alpha($char) ? $char : "#";
}
Thanks!
Use ctype_alpha to check if the first character is a letter and return accordingly:
$char = substr($rsrnum, 0, 1);
return ctype_alpha($char) ? $char : "#";
A little delayed. but I think this might do the trick just fine!
function CheckFirst($String,$CharToCheck = 1){
if ($CharToCheck < 1){
return false;
}
$First_Char = $String{$CharToCheck - 1}; // Seek first Letter of Entered String
if (ctype_alpha($First_Char) === true){
// If the first Letter is in the aplhabet (A-Z/a-z)
return "First Character Is A String";
}elseif (ctype_digit($First_Char) === true){
// If The first Letter is a digit (0-9)
return "First Character Is A Digit";
}
}
I've left the function to return a string, so it's clear what will be returned upon pushing a string to the function. Suit the returns to your requirements
Edited the function to perform a better role within the script. It can now be called to check more than the first character of a string. Defaulting to the first
In PHP, I need to write a function that takes a string and returns its conversion to a float whenever possible, otherwise just returns the input string.
I thought this function would work. Obviously the comparison is wrong, but I don't understand why.
function toNumber ($input) {
$num = floatval($input); // Returns O for a string
if ($num == $input) { // Not the right comparison?
return $num;
} else {
return $input;
}
}
echo(gettype(toNumber("1"))); // double
echo(gettype(toNumber("3.14159"))); // double
echo(gettype(toNumber("Coco"))); // double (expected: string)
function toNumber($input) {
return is_numeric($input) ? (float)$input : $input;
}
try if($num){return $num;}else{return $input}, this will work fine, it will only jump to else statement part, when $num = 0
Well the fastest thing would be checking if $num == 0 rather than $num == $input, if I understand this correctly.
I was just wondering if PHP has a function that can take a string like 2-1 and produce the arithmetic result of it?
Or will I have to do this manually with explode() to get the values left and right of the arithmetic operator?
I know this question is old, but I came across it last night while searching for something that wasn't quite related, and every single answer here is bad. Not just bad, very bad. The examples I give here will be from a class that I created back in 2005 and spent the past few hours updating for PHP5 because of this question. Other systems do exist, and were around before this question was posted, so it baffles me why every answer here tells you to use eval, when the caution from PHP is:
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
Before I jump in to the example, the places to get the class I will be using is on either PHPClasses or GitHub. Both the eos.class.php and stack.class.php are required, but can be combined in to the same file.
The reason for using a class like this is that it includes and infix to postfix(RPN) parser, and then an RPN Solver. With these, you never have to use the eval function and open your system up to vulnerabilities. Once you have the classes, the following code is all that is needed to solve a simple (to more complex) equation such as your 2-1 example.
require_once "eos.class.php";
$equation = "2-1";
$eq = new eqEOS();
$result = $eq->solveIF($equation);
That's it! You can use a parser like this for most equations, however complicated and nested without ever having to resort to the 'evil eval'.
Because I really don't want this only only to have my class in it, here are some other options. I am just familiar with my own since I've been using it for 8 years. ^^
Wolfram|Alpha API
Sage
A fairly bad parser
phpdicecalc
Not quite sure what happened to others that I had found previously - came across another one on GitHub before as well, unfortunately I didn't bookmark it, but it was related to large float operations that included a parser as well.
Anyways, I wanted to make sure an answer to solving equations in PHP on here wasn't pointing all future searchers to eval as this was at the top of a google search. ^^
$operation='2-1';
eval("\$value = \"$operation\";");
or
$value=eval("return ($operation);");
This is one of the cases where eval comes in handy:
$expression = '2 - 1';
eval( '$result = (' . $expression . ');' );
echo $result;
You can use BC Math arbitrary precision
echo bcsub(5, 4); // 1
echo bcsub(1.234, 5); // 3
echo bcsub(1.234, 5, 4); // -3.7660
http://www.php.net/manual/en/function.bcsub.php
In this forum someone made it without eval. Maybe you can try it? Credits to them, I just found it.
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
$string = " (1 + 1) * (2 + 2)";
echo calculate_string($string); // outputs 8
Also see this answer here: Evaluating a string of simple mathematical expressions
Please note this solution does NOT conform to BODMAS, but you can use brackets in your evaluation string to overcome this.
function callback1($m) {
return string_to_math($m[1]);
}
function callback2($n,$m) {
$o=$m[0];
$m[0]=' ';
return $o=='+' ? $n+$m : ($o=='-' ? $n-$m : ($o=='*' ? $n*$m : $n/$m));
}
function string_to_math($s){
while ($s != ($t = preg_replace_callback('/\(([^()]*)\)/','callback1',$s))) $s=$t;
preg_match_all('![-+/*].*?[\d.]+!', "+$s", $m);
return array_reduce($m[0], 'callback2');
}
echo string_to_match('2-1'); //returns 1
As create_function got deprecated and I was utterly needed an alternative lightweight solution of evaluating string as math. After a couple of hours spending, I came up with following. By the way, I did not care about parentheses as I don't need in my case. I just needed something that conform operator precedence correctly.
Update: I have added parentheses support as well. Please check this project Evaluate Math String
function evalAsMath($str) {
$error = false;
$div_mul = false;
$add_sub = false;
$result = 0;
$str = preg_replace('/[^\d\.\+\-\*\/]/i','',$str);
$str = rtrim(trim($str, '/*+'),'-');
if ((strpos($str, '/') !== false || strpos($str, '*') !== false)) {
$div_mul = true;
$operators = array('*','/');
while(!$error && $operators) {
$operator = array_pop($operators);
while($operator && strpos($str, $operator) !== false) {
if ($error) {
break;
}
$regex = '/([\d\.]+)\\'.$operator.'(\-?[\d\.]+)/';
preg_match($regex, $str, $matches);
if (isset($matches[1]) && isset($matches[2])) {
if ($operator=='+') $result = (float)$matches[1] + (float)$matches[2];
if ($operator=='-') $result = (float)$matches[1] - (float)$matches[2];
if ($operator=='*') $result = (float)$matches[1] * (float)$matches[2];
if ($operator=='/') {
if ((float)$matches[2]) {
$result = (float)$matches[1] / (float)$matches[2];
} else {
$error = true;
}
}
$str = preg_replace($regex, $result, $str, 1);
$str = str_replace(array('++','--','-+','+-'), array('+','+','-','-'), $str);
} else {
$error = true;
}
}
}
}
if (!$error && (strpos($str, '+') !== false || strpos($str, '-') !== false)) {
$add_sub = true;
preg_match_all('/([\d\.]+|[\+\-])/', $str, $matches);
if (isset($matches[0])) {
$result = 0;
$operator = '+';
$tokens = $matches[0];
$count = count($tokens);
for ($i=0; $i < $count; $i++) {
if ($tokens[$i] == '+' || $tokens[$i] == '-') {
$operator = $tokens[$i];
} else {
$result = ($operator == '+') ? ($result + (float)$tokens[$i]) : ($result - (float)$tokens[$i]);
}
}
}
}
if (!$error && !$div_mul && !$add_sub) {
$result = (float)$str;
}
return $error ? 0 : $result;
}
Demo: http://sandbox.onlinephpfunctions.com/code/fdffa9652b748ac8c6887d91f9b10fe62366c650
Here is a somewhat verbose bit of code I rolled for another SO question. It does conform to BOMDAS without eval(), but is not equipped to do complex/higher-order/parenthetical expressions. This library-free approach pulls the expression apart and systematically reduces the array of components until all of the operators are removed. It certainly works for your sample expression: 2-1 ;)
preg_match() checks that each operator has a numeric substring on each side.
preg_split() divides the string into an array of alternating numbers and operators.
array_search() finds the index of the targeted operator, while it exists in the array.
array_splice() replaces the operator element and the elements on either side of it with a new element that contains the mathematical result of the three elements removed.
** updated to allow negative numbers **
Code: (Demo)
$expression = "-11+3*1*4/-6-12";
if (!preg_match('~^-?\d*\.?\d+([*/+-]-?\d*\.?\d+)*$~', $expression)) {
echo "invalid expression";
} else {
$components = preg_split('~(?<=\d)([*/+-])~', $expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
var_export($components); // ['-11','+','3','*','1','*','4','/','-6','-','12']
while (($index = array_search('*',$components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] * $components[$index + 1]);
var_export($components);
// ['-11','+','3','*','4','/','-6','-','12']
// ['-11','+','12','/','-6','-','12']
}
while (($index = array_search('/', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] / $components[$index + 1]);
var_export($components); // [-'11','+','-2','-','12']
}
while (($index = array_search('+', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] + $components[$index + 1]);
var_export($components); // ['-13','-','12']
}
while (($index = array_search('-', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] - $components[$index + 1]);
var_export($components); // [-25]
}
echo current($components); // -25
}
Here is a demo of the BOMDAS version that uses php's pow() when ^ is encountered between two numbers (positive or negative).
I don't think I'll ever bother writing a version that handles parenthetical expressions ... but we'll see how bored I get.
You can do it by eval function.
Here is how you can do this.
<?php
$exp = "2-1;";
$res = eval("return $exp");
echo $res; // it will return 1
?>
You can use $res anywhere in the code to get the result.
You can use it in form by changing $exp value.
Here is an example of creating a web calculator.
<?php
if (isset($_POST['submit'])) {
$exp = $_POST['calc'];
$res = eval("return $exp;"); //Here we have to add ; after $exp to make a complete code.
echo $res;
}
?>
// html code
<form method="post">
<input type="text" name="calc">
<input type="submit" name="submit">
</form>