I use document.getElementById("text").value.length to get the string length through javascript, and mb_strlen($_POST['text']) to get the string length by PHP and both differs very much. Carriage returns are converted in javascript before getting the string length, but I guess some characters are not being counted.
For example,
[b]15. Umieszczanie obrazka z logo na stronie zespołu[/b]
This block of text is calculated 57 in javascript and 58 in PHP. When the text gets long, the difference increases. Is there any way to overcome this?
If you're trying to get the length of an UTF-8 encoded string in PHP, you should specify the encoding in the second parameter of mb_strlen, like so:
mb_strlen($_POST['text'], 'UTF-8')
Also, don't forget to call stripslashes on the POST-var.
I have found an mb_strlen equivalent function for Javascript, maybe this might be useful for someone else:
function mb_strlen(str) {
var len = 0;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? 2 : 1;
}
return len;
}
Thanks to all that tried to help!
I notice that there is a non-standard character in there (the ł) - I'm not sure how PHP counts non-standard - but it could be counting that as two. What happens if you run the test without that character?
This should do the trick
function mb_strlen (s) {
return ~-encodeURI(s).split(/%..|./).length;
}
Just type more than one line in your text area and you'll see the diference going bigger and bigger...
This came from the fact Javascript value.length don't count the end of line when all PHP length functions take them in account.
Just do:
// In case you're using CKEditot
// id is the id of the text area
var value = eval('CKEDITOR.instances.'+id+'.getData();');
// String length without the CRLF
var taille = value.length;
// get number of line
var nb_lines = (value.match(/\n/g) || []).length;
// Now, this value is the same you'll get with strlen in PHP
taille = taille + nb_lines;
Related
I am trying to convert a hex string into a signed integer.
I am able to easily transfer it into an unsigned value with hexdec() but this does not give a signed value.
Edit:
code in VB - the two "AA" hex values are representative.
Dim bs(2) As Byte
bs(1) = "AA"
bs(2) = "AA"
Dim s As Short
s = BitConverter.ToInt16(bs, 1)
Check out this comment via php.net:
hexdec() returns unsigned integers. For example hexdec("FFFFFFFE") returns 4294967294, not -2. To convert to signed 32-bit integer you may do:
<?php
echo reset(unpack("l", pack("l", hexdec("FFFFFFFE"))));
?>
As said on the hexdec manual page :
The function can now convert values
that are to big for the platforms
integer type, it will return the value
as float instead in that case.
If you want to get some kind of big integer (not float), you'll need it stored inside a string... This might be possible using BC Math functions.
For instance, if you look in the comments of the hexdec manual page, you'll find this note
If you adapt that function a bit, to avoid a notice, you'll get :
function bchexdec($hex)
{
$dec = 0;
$len = strlen($hex);
for ($i = 1; $i <= $len; $i++) {
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
}
return $dec;
}
(This function has be copied from the note I linked to ; and only a bit adapted by me)
And using it on your number :
$h = 'D5CE3E462533364B';
$f = bchexdec($h);
var_dump($f);
The output will be :
string '15406319846273791563' (length=20)
So, not the kind of big float you had ; and seems OK with what you are expecting :
Result from calc.exe =
15406319846273791563
Hope this help ;-)
And, yes, user notes on the PHP documentation are sometimes a real gold mine ;-)
I've been trying to find a decent answer to this question and so I wrote this function which works well for a Hex string input, returning a signed decimal value.
public function hex_to_signed_int($hex_str){
$dec = hexdec($hex_str);
//test is value negative
if($dec & pow(16,strlen($hex_str))/2 ){ return $dec-pow(16,strlen($hex_str));}
return $dec;
}
I am very new face to PHP. I read that dechex(255) will give the corresponding hex value ff in PHP.
I need the hex value of -105. I tried dechex(-105) and got the result as ffffff97. But I just only want 97 to do some kind of stuffs.
In Java I know that a bit wise operation with 0xff gave us the result 97 that is (byte)-105 & (byte)0xff = 0x97.
Please to find the solution in PHP just like I've done in Java.
You can do it in php like this:
var_dump(dechex(-105 & 255))
to make it out of the final byte (example output below)
string(2) "97"
dechex() gives you a hexadecimal value for a decimal value between 0 and 2*PHP_INT_MAX+1 (unsigned int).
Anything below 0 or above 2*PHP_INT_MAX+1, will loop.
-105 is NOT 0xffffff97 , and it is not 0x97
0xffffff97 is 4294967191.
and 0x97 is 151.
If you want the hexadecimal representation of the negative number turned into a positive number, use the function abs().
$abs = abs(-105); // $abs becomes +105
$hex = dechex($abs); // $hex becomes 69
Either you want a binary negative value (ffffff97) or a signed value
// for a signed value
$i = -105;
if($i < 0)
echo '-'.dechex(abs($i));
else echo dechex($i);
If you want to remove front "f"
echo preg_replace('#^f+#', '', dechex($i));
I have to translate two Python functions into PHP. The first one is:
def listspaces(string):
return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]
I am assuming that this will check for space in provided string and return True when first occurrence of space is found, is this correct ?
What is i-1 here ? is it -1 ?
In PHP we use [] for arrays . Here we are [] with return, will this function return true or false or array of locations of spaces ?
Second function is
def trimcopy(copy, spaces, length=350):
try:
if len(copy) < length:
return copy
else:
loc = 0
for space in spaces:
if space < length:
loc = space
else:
return copy[:loc]
except :
return None
Whats for space in spaces: here and whats is this return copy[:loc]
I think a good process for these type of conversions is:
work out what the code is doing
refactor it into a PHP-style in Python (this enables you to check that the logic still works, e.g. using assertion tests). e.g. convert list comprehensions to for loops
convert to PHP
For example, listspaces(string) returns the positions of spaces in string, and although using a list comprehension is Pythonic, it's not very "PHP-onic".
def listspaces2(string): #PHP-onic listspaces
space_positions = []
for i in range(len(string))]:
if string[i] == ' ':
space_positions.append(i)
return space_positions
The second example, trimcopy is rather trickier (since the try, except may purposefully be catching some expected - to the writer (!) - exceptions - two possibles are string not having a len and spaces containing values longer than len(copy)), but it's hard to say so it's a good idea to refactor in Python and test.
You can do array slicing in PHP like copy[:loc] using array_slice($copy, 0, $loc);.
Note: usually in Python we would state explicitly which exception we are defending against (as opposed to Pokemon exception handling).
You may notice that the first function could also have been written as
def listspaces(str):
return [i for i, c in enumerate(str) if c==' ']
That version has the following straightforward conversion to PHP:
function listspaces($str) {
$spaces = array();
foreach (str_split($str) as $i => $chr)
if ($chr == ' ') $spaces[] = $i;
return $spaces;
}
As for the other function, this seems to do the same thing in very nearly the same idiom:
function trimcopy($copy, $spaces, $length=350) {
if (strlen($copy) < $length) {
return $copy;
} else {
foreach ($spaces as $space) {
if ($space < $length) {
$loc = $space;
} else {
return substr($copy, 0, $loc);
}
}
}
}
As others have pointed out, the intent of both of these functions could probably be better expressed by using wordwrap.
Why don't you just test those functions to see what they are doing?
listspaces(string) returns an array with the positions of all spaces within the string:
$ ipython
IPython 0.10.2 -- An enhanced Interactive Python.
In [1]: def listspaces(string):
...: return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]
...:
In [2]: listspaces('Hallo du schöne neue Welt!')
Out[2]: [5, 8, 16, 21]
(i -1 is the position of a space when starting to count with zero)
I don't know much about Python and I can't paste the second function as there are to many "IndentationError"'s.
I think that trimcopy() will return a string (from input copy), where everything behind the last space position given in the array spaces (obviously a return value from listspaces()) is trimmed, unless the input is no longer than length.
In other words: the input is cut off at the highest space position that is smaller than length.
As of the example above, the part ' Welt!' will get cut off:
s = 'Hallo du schöne neue Welt!'
trimcopy( s, listspaces( s ) )
/* should return: 'Hallo du schöne neue' */
The first function returns indexes of all spaces in given string.
range(len(string)) results in list with numbers from 0 to length of the input string
if string.startswith(' ', i-1)] condition is evaluated for each index i, it returns true when string (here it is not a keyword) starts with ' ' at position given by the index i-1
The result is as feela posted.
For the second function I don't know what the spaces parameter is.
Hope this will help you to create a PHP version.
This is equivalent to both the functions in Python
list($short) = explode("\n",wordwrap($string,350));
This is not about security. It is also not to make it hard to break. I'm looking for a simple algorithm to change a string (a url) in a way it does not resemble the original. The encryption will be done with javascript. Then I want to feed the encrypted string to a PHP function to change it back to the original. Both ends could share a secret key, or the conversions could be key-less and rely on just logic.
The ideal solution
will be simple
will use available javascript functions for encryption
will use available php functions for decryption
will produce encrypted string in way not to resemble the plain text at all
will only use lower-case alphabet characters and numbers in the encrypted string
is not a method widely used like Base64-ing as encryption.
Edit: The last requirement was added after shamittomar's answer.
You can use bitwise XOR in javascript to encode the string and again in PHP to decode it again. I wrote a little Javascript example for you. It works the same in PHP. If you call enc() a second time with the already encoded string, you'll get the original string again.
<html>
<head><title></title></head>
<body>
<script type="text/javascript">
function enc(str) {
var encoded = "";
for (i=0; i<str.length;i++) {
var a = str.charCodeAt(i);
var b = a ^ 123; // bitwise XOR with any number, e.g. 123
encoded = encoded+String.fromCharCode(b);
}
return encoded;
}
var str = "hello world";
var encoded = enc(str);
alert(encoded); // shows encoded string
alert(enc(encoded)); // shows the original string again
</script>
</body>
</html>
In PHP do something like this (caution, this is not tested and it's been a long while since I did PHP):
$encoded = "..."; // <-- encoded string from the request
$decoded = "";
for( $i = 0; $i < strlen($encoded); $i++ ) {
$b = ord($encoded[$i]);
$a = $b ^ 123; // <-- must be same number used to encode the character
$decoded .= chr($a)
}
echo $decoded;
If that's what you want, you can Base64 encode and decode that.
[EDIT]: After OP clarification:
As you do not want widely used methods, here is one rarely used method and that can do it for you by giving output only in LOWERCASE letters and NUMBERS. It is Base32 Encode/Decode. Use the following libraries:
Javascript Base32 Encoder: http://www.tumuski.com/2010/04/nibbler/
PHP Base32 Decoder: https://www.phpclasses.org/package/3484-PHP-Encode-and-decode-data-with-MIME-base-32-encoding.html
If it's not about security, and not about making it hard to break, then how about ROT-13?
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/string/rot13 [rev. #1]
String.prototype.rot13 = function(){
return this.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
};
...
var s = "My String";
var enc = s.rot13(); // encrypted value in enc
PHP has a native function, str_rot13: http://php.net/manual/en/function.str-rot13.php
$decrypted = str_rot13($_GET['whatever']);
Well I found this page and found Redcully's program not work for me so I thought It happens with all others. finally I got reason and fixed it. Here new code is...
Thanks to Redcully :)
JS function:
function encode(str) {
var encoded = "";
for (i=0; i<str.length;i++) {
var a = str.charCodeAt(i);
var b = a ^ 51; // bitwise XOR with any number, e.g. 123
encoded = encoded+String.fromCharCode(b);
}
return encoded;
}
PHP function:
function decode($encoded) {
$decoded = "";
for( $i = 0; $i < strlen($encoded); $i++ ) {
$b = ord($encoded[$i]);
$a = $b ^ 51; // <-- must be same number used to encode the character
$decoded .= chr($a);
}
return $decoded;
}
How are you planning to implement (hide) the secret in Javascript? IMHO it's not possible.
Edit: OK - not about security.. then just use any baseXX or rot encoding mechanism. But you can't really say one of these algorythms would not be well known...
In PHP, I can use the strpbrk function to determine if a certain string contains a certain set of characters. Is there a way to do that in JavaScript?
TIA.
Edit: for those who may know JS but not PHP, strpbrk takes an input string and a string containing what you want to match as its arguments, and returns a string starting from the first character found if a match if found, or false if one isn't.
Any time I need an equivielent php function in JavaScript, i turn to php.js
Most of the functions have no dependencies and can be cut n pasted at will.
See here: Javascript equivalent for PHP's strpbrk
function strpbrk (haystack, char_list) {
// http://kevin.vanzonneveld.net
// + original by: Alfonso Jimenez (http://www.alfonsojimenez.com)
// + bugfixed by: Onno Marsman
// + revised by: Christoph
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: strpbrk('This is a Simple text.', 'is');
// * returns 1: 'is is a Simple text.'
for (var i = 0, len = haystack.length; i < len; ++i) {
if (char_list.indexOf(haystack.charAt(i)) >= 0) {
return haystack.slice(i);
}
}
return false;
}
Yes
For those playing the home game, http://phpjs.org is a fantastic site with many contributors who are working to have a major portion of the PHP base function API available in JavaScript. You can download individual functions, or you can get packages of many functions.
EDIT: For all those of you posting to http://kevin.vanzonneveld.net note that the new main site for the functions is http://www.phpjs.org
function strpbrk(string, chars) {
for(var i = 0, len = string.length; i < len; ++i) {
if(chars.indexOf(string.charAt(i)) >= 0)
return string.substring(i);
}
return false;
}