<?php
$s = "pa99";
$s++;
echo $s;
?>
The above code outputs to "pb00"
What i wanted was "pa100" and so on.
But also in case its "pa", I want it to go to "pb" which works well with
increment operator.
You are, as Michael says, trying to increment a string - it Does Not Work That Way (tm). What you want to do is this:
<?php
$s = "pa"; //we're defining the string separately!
$i = 99; //no quotes, this is a number
$i++;
echo $s.$i; //concatenate $i onto $s
?>
There's no automated way to increment a string (aa, ab, etc) the way you're asking. You could turn each letter into a number between 1-26 and increment them, and then increment the previous one on overflow. That's kind of messy, though.
To separate the integer from the string, try this:
PHP split string into integer element and string
From the docs:
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.
<?php
$s_letter = substr($s,0,2);
$s_number = substr($s,2,9);
$s_letter++; $s_number++;
$s_result = $s_letter.$s_number;
echo $s_result;
?>
Related
I have a php string like:
$string = '1234532323%A73823823221A%221312373712';
the string has numbers and 2 special tags (%A and A%) to indicate the begin and the end of the special part, respectively.
My goal is to replace all "1" with "2", but not in the part of the string between %A and A%.
If I use strtr(string,"1","2") all 1 occurrences will be replaced.
Does anyone know how my goal can be achieved?
Special characters may appear several times inside the string.
well you can use this algorithm
note: it's not written in any programmation language
int test = 0;
for(int i=0;i<ch.length();i++){
if(test!=1 && ch(i)!="%"){
if(ch(i)==1)
ch(i)=2;
}else
{
test++;
}
}
Sorry for the bad presentation..
You can do that by breaking them apart and replacing the strings. do look into preg_* to better solve all cases.
$a = "1234532323%A73823823221A%221312373712";
//explode to an array of 3 objects
$b = explode('%',$a);
//replace the numbers in the first and last object
$b[0] = strtr($b[0],"1","2");
$b[2] = strtr($b[2],"1","2") ;
//concatenate them again to get $a
$a = $b[0].$b[1].$b[2];
echo($a);
How can I convert a PHP hex array, to ascii?
Ex. if I have this string:
$var1="\x76\x52\x9\x3a\x5b\x79";
When I echo it, it appears right, but I'd like to convert it to ascii in the program, so I can do further processing on it & use it further in the script.
The string is already as you want it. The hex notation is just that: a notation. In reality the string has 6 characters:
echo strlen($var1);
Output:
6
And this:
echo $var1 === "vR\t:[y";
Outputs:
1
Which means they are equal. Note that I still had to escape the tab character with a backslash, but also that is just notation. In reality the tab character is there and is one character.
You can try this code
<?php
$var1 = '\x76\x52\x9\x3a\x5b\x79';
echo hexa_string($var1);
function hexa_string($hex_str)
{
$string='';
for ($i=0; $i < strlen($hex_str)-1; $i+=2)
{
$string .= chr(hexdec($hex_str[$i].$hex_str[$i+1]));
}
return $string;
}
?>
Double quotes--->"$a" interpretes variables.
single quotes--->'$a' does not.Alright till now
MyQuestion:
what if I use "'$a'"?
Note:want to know behind the scene details.
Detailed Explanation:
I faced a major problem because of this when I used it in a foreach loop:
The following example gave me incorrect option value. For example, value it renders is UX if original is UX developer
echo "<option value=".$item['m_designation'].">".$item['m_designation']."</option>";
this example gave me correct option value. For example,value it renders is UX developer if original is UX developer
echo '<option value="'.$item['m_designation'].'"> '.$item['m_designation'].' </option>';
Hope I am clear.
Update:
I got the desired result but I don't know the logic behind it. I have tried it and done it successfully, but I wanted to know what's happening behind the scene. I think people have misread my question.
The use of ' and " for strings only changes when they are the outer container of the entire string - a different quote inside that is just treated as a plain character with no special meaning, therefore "'$var'" uses the rules of " (parsing variables), whereas '"$var"' would literally output "$var" as it uses the rules of ' (no parsing of variables).
Summary:
When you do "''" or "\"\"" the quotes inside the string are not parsed by PHP and treated as literal characters, the contents of such quotes will have the same behaviour in or out of those quotes.
You'll have a string that uses double quotes as delimiters and has single quotes as data. The delimiters are the ones that matter for determining how a string will be handled.
$a = 'test';
echo '$a';// prints $a
echo "$a";// prints test
echo "'$a'"//prints 'test'
double quotes checks the php variable and echo the string with php variable value
example echo "wow $a 123"; //prints wow test 123
single quotes print whatever in the single quotes
example echo 'foo $a 123';//prints foo $a 123
Your 'faulty' (first) string was missing the single quotes ':
echo "<option value='".$item['m_designation']."'>".$item['m_designation']."</option>";
^ ^
Your problem is that you confuse the quotes in your HTML with the quotes in the PHP.
$a = 1;
$b = '"$a"';
echo $b;
# => "$a"
$a = 1;
$b = "\"$a\"";
echo $b;
# => "1"
I'd advise you to simply never use string literals, as (especially in PHP) there are a lot of unexpected and weird edge-cases to them. Best is to force an interpreter (which also only works with double quotes:
$a = 1;
$b = "\"{$a}\"";
$c = "{$a+2}";
echo $b;
# => "1"
echo $c;
# => 3
It seems your question is more directed toward the output PHP produces for HTML formatting. Simply, single quotes in PHP represent the literal value:
$a = 1;
$b = '$a';
echo $b;
//$a
$a = 1;
$b = "$a";
echo $b;
//1
$a = 1;
$b = "'$a'";
echo $b;
//'1'
If you want to output HTML, you can use heredoc syntax. This is useful when outputting more than one line containing variables:
$name = "Bob";
$age = 59;
echo <<<EOT
My name is "$name".
I am $age years old.
EOT;
//My name is "Bob"
//I am 59 years old.
PHP.net's documentation on the range function is a little lacking. These functions produce unexpected (to me anyways) results when given character ranges.
$m = range('A','z');
print_r($m);
$m = range('~','"');
print_r($m);
I'm looking for a reference that might explicitly define its behavior.
The issue is that range treats its arguments like integers, and if you give it a single character it will convert it to its ASCII character code.
In the first case, you're getting all characters between character 'A' (integer 65) and character 'z' (integer 122). This is expected behavior for those of us coming from a C (or C-like language) background.
This is one of the rare cases where PHP converts single characters to their ASCII codes rather than parsing the string as integer the way it does normally. Most of the PHP documentation is better at telling you when to expect this. strpos for example, notes:
Needle
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The documentation for range is strangely quiet about it.
Consider:
foreach (range('A','z') as $c)
echo $c."\n";
to be equivalent to:
for ($i = ord('A'); $i <= ord('z'); ++$i)
echo chr($i)."\n";
Likewise, your second example is equivalent to (since ord('~') > ord('"')):
for ($i = ord('~'); $i >= ord('"'); --$i)
echo chr($i)."\n";
It's not well documented, but that's how it is supposed to work.
that is because " is a lower character than ~ try
m = range('A','z'); print_r($m);
$m = range('z','A'); print_r($m);
the characters are pulled by their chr (ASCII Table) values:
http://www.asciitable.com/
the array is returned in the directional order of the 2 parameters.
I have a form in which people will be entering dollar values.
Possible inputs:
$999,999,999.99
999,999,999.99
999999999
99,999
$99,999
The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.
I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:
$string1 = "$50,000";
$string2 = "$50000";
$string3 = "50,000";
$total = (double)$string1 + (double)$string2 + (double)$string3;
echo $total;
A regex won't convert your string into a number. I would suggest that you use a regex to validate the field (confirm that it fits one of your allowed formats), and then just loop over the string, discarding all non-digit and non-period characters. If you don't care about validation, you could skip the first step. The second step will still strip it down to digits and periods only.
By the way, you cannot safely use floats when calculating currency values. You will lose precision, and very possibly end up with totals that do not exactly match the inputs.
Update: Here are two functions you could use to verify your input and to convert it into a decimal-point representation.
function validateCurrency($string)
{
return preg_match('/^\$?(\d{1,3})(,\d{3})*(.\d{2})?$/', $string) ||
preg_match('/^\$?\d+(.\d{2})?$/', $string);
}
function makeCurrency($string)
{
$newstring = "";
$array = str_split($string);
foreach($array as $char)
{
if (($char >= '0' && $char <= '9') || $char == '.')
{
$newstring .= $char;
}
}
return $newstring;
}
The first function will match the bulk of currency formats you can expect "$99", "99,999.00", etc. It will not match ".00" or "99.", nor will it match most European-style numbers (99.999,00). Use this on your original string to verify that it is a valid currency string.
The second function will just strip out everything except digits and decimal points. Note that by itself it may still return invalid strings (e.g. "", "....", and "abc" come out as "", "....", and ""). Use this to eliminate extraneous commas once the string is validated, or possibly use this by itself if you want to skip validation.
You don't ever want to represent monetary values as floats!
For example, take the following (seemingly straight forward) code:
$x = 1.0;
for ($ii=0; $ii < 10; $ii++) {
$x = $x - .1;
}
var_dump($x);
You might assume that it would produce the value zero, but that is not the case. Since $x is a floating point, it actually ends up being a tiny bit more than zero (1.38777878078E-16), which isn't a big deal in itself, but it means that comparing the value with another value isn't guaranteed to be correct. For example $x == 0 would produce false.
http://p2p.wrox.com/topic.asp?TOPIC_ID=3099
goes through it step by step
[edit] typical...the site seems to be down now... :(
not a one liner, but if you strip out the ','s you can do: (this is pseudocode)
m/^\$?(\d+)(?:\.(\d\d))?$/
$value = $1 + $2/100;
That allows $9.99 but not $9. or $9.9 and fails to complain about missplaced thousands separators (bug or feature?)
There is a potential 'locality' issue here because you are assuming that thousands are done with ',' and cents as '.' but in europe it is opposite (e.g. 1.000,99)
I recommend not to use a float for storing currency values. You can get rounding errors if the sum gets large. (Ok, if it gets very large.)
Better use an integer variable with a large enough range, and store the input in cents, not dollars.
I belive that you can accomplish this with printf, which is similar to the c function of the same name. its parameters can be somewhat esoteric though. you can also use php's number_format function
Assuming that you are getting real money values, you could simply strip characters that are not digits or the decimal point:
(pseudocode)
newnumber = replace(oldnumber, /[^0-9.]/, //)
Now you can convert using something like
double(newnumber)
However, this will not take care of strings such as "5.6.3" and other such non-money strings. Which raises the question, "Do you need to handle badly formatted strings?"