I have a file that contains data (keywords) to interpret and starts with 4-bytes big endian to determine number of keywords. I can't seem to get the proper integer value from it.
$bytes = "00000103";
$keywords = preg_replace("/(.{2})(.{2})(.{2})(.{2})/u", "\x$1\x$2\x$3\x$4", $bytes);
var_dump($keywords);
$unpacked = unpack("N", $keywords);
var_dump($unpacked);
Outputs (incorrect):
string(16) "\x00\x00\x01\x03"
array(1) {
[1]=>
int(1551380528)
}
For testing purposes, I change the $keywords variable to:
$bytes = "\x00\x00\x01\x03";
It outputs (correct):
string(4) ""
array(1) {
[1]=>
int(259)
}
How do I change the data-type of $keywords? Searched a lot, but can't get it to work unfortunately.
PS. After posting, it doesn't show the 2 characters (boxes with questionmarks) in them in the correct output for string(4).
You can simply use the hexdec-function:
$bytes = "00000103";
$dec = hexdec($bytes);
var_dump($dec); //int(259)
Related
I want to create a function which generates specific patterns to describe a numeric range between two given numbers. The function accepts two parameters: $startNumber and $endNumber. It should return an array of pattern strings. The best way to describe it is with examples:
myfunction(00000, 99999) = array('*');
myfunction(10000, 29999) = array('1*', '2*');
myfunction(68000, 68999) = array('68*');
myfunction(0004000, 0008999) = array('0004*', '0005*', '0006*', '0007*', '0008*');
myfunction(5570000, 5659999) = array('557*', '558*', '559*', '560*', '561*', '562*', '563*', '564*', '565*');
myfunction(3760000, 5259999) = array('376*', '377*', '378*', '379*', '38*', '39*', '4*', '50*', '51*', '520*', '521*', '522*', '523*', '524*', '525*');
myfunction(12345, 45678) = array('12345*', '12346*', '12347*', '12348*', '12349*', '1235*', '1236*', '1237*', '1238*', '1239*', '124*', '125*', '126*', '127*', '128*', '129*', '13*', '14*', '15*', '16*', '17*', '18*', '19*', '2*', '3*', '40*', '41*', '42*', '43*', '44*', '450*', '451*', '452*', '453*', '454*', '455*', '4560*', '4561*', '4562*', '4563*', '4564*', '4565*', '4566*', '45670*', '45671*', '45672*', '45673*', '45674*', '45675*', '45676*', '45677*', '45678*');
myfunction(000000, 399099) = array('0*', '1*', '2*', '30*', '31*', '32*', '33*', '34*', '35*', '36*', '37*', '38*', '390*', '391*', '392*', '393*', '394*', '395*', '396*', '397*', '398*', '3990*');
Since some parts of your issue are not clear,
I'll get closer to the first need you are claiming...
For the range
You don't need to recode the existing ;-)
Look for range() native function, can already do that for you:
function myfunction($start, $end)
{
$r = range($start, $end);
return array_map(function($n)
{
return $n.'*';
}, $r);
}
var_dump(myfunction(34, 39));
// will output:
array(6) {
[0]=>
string(3) "34*"
[1]=>
string(3) "35*"
[2]=>
string(3) "36*"
[3]=>
string(3) "37*"
[4]=>
string(3) "38*"
[5]=>
string(3) "39*"
}
Note: I can't use break or next line functions as i am using FPDF
I am having a problem with php strings. I am having a string where i want to show atmost 12 characters in first row and remaining in second row. So basically i want to break string into two parts and assign to two variables so that i can print those two variables. I have tried following code :-
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 12);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
But using this I am getting as shown below :
Original String : The Best Hotel Ever
Output :
The Best Hot
Tel Ever
It is breaking a word, i don't want to break the word, just check the length and if within 12 characters all the words are complete then print next word in next line. Like this :
Desired OutPut:
The Best
Hotel Ever
Any suggestions ?
I see no built-in function to do it, however you could explode on spaces, and re-build your string until the length with the next words get over 12, everything else going to the second part :
$string = 'The Best Hotel Ever';
$exp = explode(' ', $string);
if (strlen($exp[0]) < 12) {
$tmp = $exp[0];
$i = 1;
while (strlen($tmp . ' ' . $exp[$i]) < 12) {
$tmp .= " " . $exp[$i];
$i++;
}
$array[0] = $tmp;
while (isset($exp[$i])) {
$array[1] .= ' ' . $exp[$i];
$i++;
}
$array[1] = trim($array[1]);
} else {
$array[0] = '';
$array[1] = trim(implode (' ', $exp));
}
var_dump($array);
// Output : array(2) { [0]=> string(8) "The Best" [1]=> string(10) "Hotel Ever" }
// $string1 = 'The';
// array(2) { [0]=> string(3) "The" [1]=> string(0) "" }
// $string2 = 'Thebesthotelever';
// array(2) { [0]=> string(0) "" [1]=> string(16) "Thebesthotelever" }
Im not too crash hot on PHP but it seems to be a simple case of which element of the string you are accessing is futher across from where you want to be:
Try:
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 8);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
For further help check out because you need to remember to count from zero up:
http://php.net/manual/en/function.substr.php
I have stored in MySQL the number as total(decimal 16,2) 1423.28
I get it display from PHP after making some calculations:
function calculate_balance($total){
//get total paid from another function
$total_paid = ...
if ($total_paid == 0){
return $total;
}else{
return $total-$total_paid
}
}
$balance = calculate_balance($total);
echo number_format($balance, 2); //returns 1.00
I have tried
number_format((float)$balance, 2);
number_format(floatval($balance), 2);
UPDATE
var_dump($balance)
and I got following output.
string(8) "1,423.28" float(152) string(6) "252.00" string(6) "247.50" string(6) "247.50" string(6) "247.50" string(6) "549.90" string(6) "495.00" float(0) string(6) "284.76" float(265)
It's working fine without number_format() for value under 1,000.
E.g.: if balance equal 252.00
echo $balance;
output
252.00
Your function returns 1,423.28? This is not a float, as a float does never contain a comma as a thousands-separator.
PHP interprets this as 1, because it "breaks" at the comma.
Remove the comma and you are fine!
$balance = str_replace(',', '', $balance);
Following the answer of Lars Evert I used the function number_format like that
number_format($balance, 2, '.', '');
and that solved my problem
If the string is bigger then 50 chars long, I need to split it.
The maximum allowed is 3 chunks of 50. It could be less then 50 but never more then 150.
I don't need any special chars to be added, or to serve as "splitters"; I can break the string anywhere, no problem, since the propose is not for showing it to the user.
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
}
Is there a more elegant way for doing this?
UPDATE:
An example of what would arrive next:
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
if(!empty($streetPart2) && empty($streetPart3)
{
//add part2 only.
}elseif(!empty($streetPart2 && !empty($streetPart3))
{
//add part 2 and part 3
}
}
Thanks a lot.
MEM
You may simply use str_split:
$parts = str_split($string, 50);
// if you want to have vars instead of array:
list($part1, $part2, $part3) = str_split($string, 50);
Check the PHP's wordwrap() function.
http://php.net/manual/en/function.wordwrap.php
And check out the explode() function
http://php.net/manual/en/function.explode.php
<?
function wrapAndCropToArray($text, $width, $lines)
{
$ret = array_slice(
explode("\n",wordwrap($text,$width,"\n",true))
, 0
, $lines+1
);
if(isset($ret[$lines]))
$ret[$lines] = "...";
return $ret;
}
$test = "aadfuiosdy 34 123 412 341f2 38947 1029 384h120 39uh4 19023h 41234";
var_dump(wrapAndCropToArray($test,10,3));
?>
Will output:
array(4) {
[0]=>
string(10) "aadfuiosdy"
[1]=>
string(10) "34 123 412"
[2]=>
string(5) "341f2"
[3]=>
string(3) "..."
}
This question already has answers here:
preg_match and UTF-8 in PHP
(8 answers)
Closed 12 months ago.
I have preg_match_all('/[aäeëioöuáéíóú]/u', $in, $out, PREG_OFFSET_CAPTURE);
If $in = 'hëllo' $out is:
array(1) {
[0]=>
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "ë"
[1]=>
int(1)
}
[1]=>
array(2) {
[0]=>
string(1) "o"
[1]=>
int(5)
}
}
}
The position of o should be 4. I've read about this problem online (the ë gets counted as 2). Is there a solution for this? I've seen mb_substr and similar, but is there something like this for preg_match_all?
Kind of related: Is their an equivalent of preg_match_all in Python? (Returning an array of matches with their position in the string)
This is not a bug, PREG_OFFSET_CAPTURE refers to the byte offset of the character in the string.
mb_ereg_search_pos behaves the same way. One possibility is to change the encoding to UTF-32 before and then divide the position by 4 (because all unicode code units are represented as 4-byte sequences in UTF-32):
mb_regex_encoding("UTF-32");
$string = mb_convert_encoding('hëllo', "UTF-32", "UTF-8");
$regex = mb_convert_encoding('[aäeëioöuáéíóú]', "UTF-32", "UTF-8");
mb_ereg_search_init ($string, $regex);
$positions = array();
while ($r = mb_ereg_search_pos()) {
$positions[] = reset($r)/4;
}
print_r($positions);
gives:
Array
(
[0] => 1
[1] => 4
)
You could also convert the binary positions into code unit positions. For UTF-8, a suboptimal implementation is:
function utf8_byte_offset_to_unit($string, $boff) {
$result = 0;
for ($i = 0; $i < $boff; ) {
$result++;
$byte = $string[$i];
$base2 = str_pad(
base_convert((string) ord($byte), 10, 2), 8, "0", STR_PAD_LEFT);
$p = strpos($base2, "0");
if ($p == 0) { $i++; }
elseif ($p <= 4) { $i += $p; }
else { return FALSE; }
}
return $result;
}
There is simple workaround, to be used after preg_match() results matched. You need to iterate every match result and reassign position value with following:
$utfPosition = mb_strlen(substr($wholeSubjectString, 0, $capturedEntryPosition), 'utf-8');
Tested on php 5.4 under Windows, depends on Multibyte PHP extension only.
PHP doesn't support unicode very well, so a lot of string functions, including preg_*, still count bytes instead of characters.
I tried finding a solution by encoding and decoding strings, but ultimately it all came down to the preg_match_all function.
About the python thing: a python regex matchobject contains the match position by default mo.start() and mo.end(). See: http://docs.python.org/library/re.html#finding-all-adverbs-and-their-positions
Another way how to split UTF-8 $string by a regular expression is to use function preg_split(). Here is my working solution:
$result = preg_split('~\[img/\d{1,}/img\]\s?~', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
PHP 5.3.17