Tuesday, 7 June 2016

fflush

18.18. Flushing Output to a File

18.18.1. Problem
You want to force all buffered data to be written to a filehandle.

18.18.2. Solution
Use fflush( ):

    fwrite($fh,'There are twelve pumpkins in my house.');
    fflush($fh);

This ensures that "There are twelve pumpkins in my house." is written to $fh.

18.18.3. Discussion
To be more efficient, system I/O libraries generally don't write something to a file when you tell them to. Instead, they batch the writes together in a buffer and save all of them to disk at the same time. Using fflush( ) forces anything pending in the write buffer to be actually written to disk.
Flushing output can be particularly helpful when generating an access or activity log. Calling fflush( ) after each message to log file makes sure that any person or program monitoring the log file sees the message as soon as possible.

18.18.4. See Also
Documentation on fflush( ) at http://www.php.net/fflush.

Friday, 3 June 2016

Questions: File functions

What is the output of following code?
<?php
$name = 'fpassthru.txt';

$str = <<<EOF
FOO
BAR
BAZ
EOF;

$fp = fopen($name, 'w');
fwrite($fp, $str);
fclose($fp);

$fp = fopen($name, 'r');
fgets($fp);
fpassthru($fp);
fclose($fp);
?>

a) FOO BAR
b) BAR BAZ
c) FOO BAZ
d) BAR FOO

Wednesday, 4 May 2016

INI configuration (SIAPS SERVER)

allow_url_fopen: 1
allow_url_include: 0
always_populate_raw_post_data: 1
arg_separator.input: ;&
arg_separator.output: &
asp_tags:
assert.active: 1
assert.bail:
assert.callback: 0
assert.quiet_eval: 0
assert.warning: 1
auto_append_file:
auto_detect_line_endings:
auto_globals_jit: 1
auto_prepend_file:
bcmath.scale: 0
browscap: extra/browscap.ini
curl.cainfo:
date.default_latitude: 31.7667
date.default_longitude: 35.2333
date.sunrise_zenith: 90.583333
date.sunset_zenith: 90.583333
date.timezone: UTC
default_charset:
default_mimetype: text/html
default_socket_timeout: 60
disable_classes:
disable_functions:
display_errors: 1
display_startup_errors:
doc_root:
docref_ext: .html
docref_root: /phpmanual/
enable_dl: 1
enable_post_data_reading: 1
engine: 1
error_append_string:
error_log: error_log
error_prepend_string:
error_reporting: 22519
exit_on_timeout: 0
expose_php: 1
extension_dir: /usr/local/lib/php/extensions/no-debug-non-zts-20100525
file_uploads: 1
filter.default: unsafe_raw
filter.default_flags:
from: john@doe.com
gd.jpeg_ignore_warning: 0
highlight.comment: #FF9900
highlight.default: #0000BB
highlight.html: #000000
highlight.keyword: #007700
highlight.string: #DD0000
html_errors:
iconv.input_encoding: ISO-8859-1
iconv.internal_encoding: ISO-8859-1
iconv.output_encoding: ISO-8859-1
ignore_repeated_errors:
ignore_repeated_source:
ignore_user_abort: 0
implicit_flush:
include_path: .:/usr/lib/php:/usr/local/lib/php
intl.default_locale:
intl.error_level: 0
last_modified: 0
log_errors: 1
log_errors_max_len: 1024
mail.add_x_header: 0
mail.force_extra_parameters:
mail.log:
max_execution_time: 60
max_file_uploads: 20
max_input_nesting_level: 64
max_input_time: 60
max_input_vars: 1000
mbstring.detect_order: auto
mbstring.encoding_translation:
mbstring.func_overload: 0
mbstring.http_input: auto
mbstring.http_output: SJIS
mbstring.http_output_conv_mimetypes: ^(text/|application/xhtml\+xml)
mbstring.internal_encoding: EUC-JP
mbstring.language: neutral
mbstring.strict_detection: 0
mbstring.substitute_character:
mcrypt.algorithms_dir:
mcrypt.modes_dir:
memory_limit: 128M
mysql.allow_local_infile: 1
mysql.allow_persistent: 1
mysql.connect_timeout: 60
mysql.default_host:
mysql.default_password:
mysql.default_port:
mysql.default_socket: /var/lib/mysql/mysql.sock
mysql.default_user:
mysql.max_links: -1
mysql.max_persistent: -1
mysql.trace_mode:
mysqli.allow_local_infile: 1
mysqli.allow_persistent: 1
mysqli.default_host:
mysqli.default_port: 3306
mysqli.default_pw:
mysqli.default_socket: /var/lib/mysql/mysql.sock
mysqli.default_user:
mysqli.max_links: -1
mysqli.max_persistent: -1
mysqli.reconnect: 0
mysqlnd.collect_memory_statistics: 0
mysqlnd.collect_statistics: 1
mysqlnd.debug:
mysqlnd.log_mask: 0
mysqlnd.mempool_default_size: 16000
mysqlnd.net_cmd_buffer_size: 4096
mysqlnd.net_read_buffer_size: 32768
mysqlnd.net_read_timeout: 31536000
opcache.blacklist_filename:
opcache.consistency_checks: 0
opcache.dups_fix: 0
opcache.enable: 1
opcache.enable_cli: 0
opcache.enable_file_override: 0
opcache.error_log:
opcache.fast_shutdown: 0
opcache.file_update_protection: 2
opcache.force_restart_timeout: 180
opcache.inherited_hack: 1
opcache.interned_strings_buffer: 4
opcache.load_comments: 1
opcache.log_verbosity_level: 1
opcache.max_accelerated_files: 2000
opcache.max_file_size: 0
opcache.max_wasted_percentage: 5
opcache.memory_consumption: 64
opcache.optimization_level: 0xFFFFFFFF
opcache.preferred_memory_model:
opcache.protect_memory: 0
opcache.restrict_api:
opcache.revalidate_freq: 2
opcache.revalidate_path: 0
opcache.save_comments: 1
opcache.use_cwd: 1
opcache.validate_timestamps: 1
open_basedir:
output_buffering:
output_handler:
pcre.backtrack_limit: 1000000
pcre.recursion_limit: 100000
pdo_mysql.default_socket: /var/lib/mysql/mysql.sock
phar.cache_list:
phar.readonly: 1
phar.require_hash: 1
phpd: 1
phpd.t: 1
post_max_size: 50M
precision: 12
realpath_cache_size: 16K
realpath_cache_ttl: 120
register_argc_argv: 1
report_memleaks: 1
report_zend_debug: 1
request_order:
sendmail_from: me@localhost.com
sendmail_path: /usr/sbin/sendmail -t -i
serialize_precision: 100
session.auto_start: 0
session.cache_expire: 180
session.cache_limiter: nocache
session.cookie_domain:
session.cookie_httponly: 1
session.cookie_lifetime: 0
session.cookie_path: /
session.cookie_secure:
session.entropy_file:
session.entropy_length: 0
session.gc_divisor: 100
session.gc_maxlifetime: 1440
session.gc_probability: 1
session.hash_bits_per_character: 4
session.hash_function: 0
session.name: PHPSESSID
session.referer_check:
session.save_handler: files
session.save_path: /tmp
session.serialize_handler: php
session.upload_progress.cleanup: 1
session.upload_progress.enabled: 1
session.upload_progress.freq: 1%
session.upload_progress.min_freq: 1
session.upload_progress.name: PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix: upload_progress_
session.use_cookies: 1
session.use_only_cookies: 1
session.use_trans_sid: 0
short_open_tag: 1
SMTP: localhost
smtp_port: 25
soap.wsdl_cache: 1
soap.wsdl_cache_dir: /tmp
soap.wsdl_cache_enabled: 1
soap.wsdl_cache_limit: 5
soap.wsdl_cache_ttl: 86400
sourceguardian.restrict_unencoded: 0
sql.safe_mode:
sqlite3.extension_dir:
tidy.clean_output: 0
tidy.default_config:
track_errors:
unserialize_callback_func:
upload_max_filesize: 50M
upload_tmp_dir:
url_rewriter.tags: a=href,area=href,frame=src,input=src,form=,fieldset=
user_agent: PHP
user_dir:
user_ini.cache_ttl: 300
user_ini.filename: .user.ini
variables_order: EGPCS
xbithack: 0
xmlrpc_error_number: 0
xmlrpc_errors: 0
xsl.security_prefs: 44
zend.detect_unicode: 1
zend.enable_gc: 1
zend.multibyte: 0
zend.script_encoding:
zend_loader.disable_licensing: 0
zend_loader.enable: 1
zend_loader.max_alloca: 2048
zend_loader.obfuscation_level_support: 0
zlib.output_compression:
zlib.output_compression_level: -1
zlib.output_handler:

Tuesday, 3 May 2016

সাব প্যাটার্ন বাদ দেওয়া এটা দ্বারা ?:

Remove subpattern from array $matches

আগে
Array
(
    [0] => xxxxzzzz
    [1] => xxxx   // remove this by ?: 
    [2] => zzzz
)
 
$str = "xxxxzzzz";
preg_match("/(x+)(z+)/",  $str, $matches);
print_r($matches); 

 
পরে 
Array
(
    [0] => xxxxzzzz
    [1] => zzzz
)

Monday, 2 May 2016

strtok

strtok বিভিন্ন ধরনের দেলিমেতের থাকে এমন স্ট্রিং কে টোকেন হিসাবে রিটার্ন করে।  repeated delimiter থাকলে প্রতি একবার রান করলে একটা টোকেন স্ট্রিং রিটার্ন করে, এভাবে পর পর রান করলে পরবার একটা করে রিটার্ন পাওয়া যাবে সংশ্লিষ্ট ওই delimiter জন্য। সুধু প্রথমবার স্ট্রিং দিতে হই, তারপর শুধু delimiter token দিলেই হয়। প্রতি executioner পর এটা কারেন্ট position ধরে রাখে।

var_dump(strtok('a1/a2/a3/a4', '/')); //a1
var_dump(strtok('/')); // a2
var_dump(strtok('/')); // a3
var_dump(strtok('/')); // a4
var_dump(strtok('/')); // bool(false) , at 5th execution

string(2) "a1"
string(2) "a2"
string(2) "a3"
string(2) "a4"
bool(false)


<?php
$string 
"This is\tan example\nstring";/* Use tab and newline as tokenizing characters as well  */$tok strtok($string" \n\t");

while (
$tok !== false) {
    echo 
"Word=$tok<br />";
    
$tok strtok(" \n\t");
}
?>

Sunday, 1 May 2016

preg_replace_callback_array

$subject 'Aaaaaa Bbb';
preg_replace_callback_array(
    [
        
'~[a]+~i' => function ($match) {
            echo 
strlen($match[0]), ' matches for "a" found'PHP_EOL;
        },
        
'~[b]+~i' => function ($match) {
            echo 
strlen($match[0]), ' matches for "b" found'PHP_EOL;
        }
    ],
    
$subject);



6 matches for "a" found
3 matches for "b" found

preg_grep

// return all array elements
// containing floating point numbers
$array = array(120, 256.2, 985, 254, 654, 85.24, 65.9, 87);
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);

print_r($fl_array);

Array
(
    [1] => 256.2
    [5] => 85.24
    [6] => 65.9
)

preg_quote

$keywords = '\ + * ? [ ^ ] $ ( ) abc { } = ! < > | : -';
$keywords = preg_quote($keywords, "abc");
echo $keywords;

Ans: \\ \+ \* \? \[ \^ \] \$ \( \) \abc \{ \} \= \! \< \> \| \: \-

preg_replace_callback

function add($matches){
    print_r($matches);
    return $matches[2]+1;
}

echo preg_replace_callback('/(1)5(7)/', "add", "777157777177");

Array
(
    [0] => 157
    [1] => 1
    [2] => 7
)
 
7778777177

preg_replace

$string = 'April 15, 2003';
$pattern = '/(April) (15), (2003)/i';
$replacement = 'Month: $1 Date: $2 Year: $3';
echo preg_replace($pattern, $replacement, $string);

$string = "The quick brown fox jumps over the lazy dog";
$patterns = array("/quick/", "/brown/", "/fox/");
$replacements = array(2=>"bear", 1=>"black", 0=>"slow");
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);

$string = 'April 15, 2003';
$pattern = '/(April) (15), (2003)/i';
$replacement = 'Month: $1 Date: $2 Year: $3';
echo preg_replace($pattern, $replacement, $string);

$count = 0;
echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3

Friday, 29 April 2016

Backreferences To Match The Same Text Again

সাব প্যাটার্ন পুনরায় না লিখে আগের সাব প্যাটার্নকে আবার কোনো সংকেতের মাধমে ব্যবহার  করাকে বলে। প্রতিটি সাব প্যাটার্নকে এক একটি ক্যাপচার গ্রুপ ধরে ক্রম অনুযায়ে ১, ২, ৩ হিসাবে ধরা হয়। অবশই প্যাটার্ন-এ সিঙ্গেল কোটো দিয়ে আটকাতে হবে।

// Subpattern
preg_match('/(php) (zend) (exam) php zend exam/', 'start php zend exam php zend exam end', $matches); //sub pattern capture group (php),(zend),(exam)
print_r($matches);
/*
Array
(
    [0] => php zend exam php zend exam
    [1] => php
    [2] => zend
    [3] => exam
)
 */


//Backreference using subpattern
preg_match('/(php) (zend) (exam) \1 \2 \3/', 'start php zend exam php zend exam end', $matches); //sub pattern capture group (php)=1,(zend)=2,(exam)=3 (for backreference)
print_r($matches);
/*
Array
(
    [0] => php zend exam php zend exam
    [1] => php
    [2] => zend
    [3] => exam
)
 */

//Backreference of (sens|respons) is the first position 1, so it is \1
preg_match_all('/(sens|respons)e and \1ibility/', "sense and sensibility", $matches);
print_r($matches);

$string = 'My String <span>55 PKR</span> is valid';
$string = preg_replace('/<(span>).+?<\/\1/', '', $string);
echo $string;  // My String is valid

Tuesday, 22 March 2016

Named Subpattern

নেমড প্যাটার্ন এর নাম ইনডেক্স হিসাবে এরে তে রিটার্ন করে, এটা অনেকটা সাব প্যাটার্ন এর মত কাজ করে কিন্তু সিনটেক্স ভিন্ন। দুই ধরনের সিনটেক্স আছে এতে। 

 <?php
$str = "Year: 2016";
preg_match('/(?<Name>\w+): (?<Value>\d+)/', $str, $matches);
// OR preg_match('/(?P<Name>\w+): (?P<Value>\d+)/', $str, $matches);
print_r($matches);
?>

Output:
Array
(
    [0] => Year: 2016
    [Name] => Year
    [1] => Year
    [Value] => 2016
    [2] => 2016
)

Question Set 1

1. $pattern = "GHI";
$subject = "ABCDEFGHIJKLMN";
If you find the pattern "GHI" which is the faster way to find it?

a) preg_match()
b) strpos

Ref: http://php.net/manual/en/function.preg-match.php
==================================================

2.

Getting the domain name out of a URL

( এ ক্ষেত্রে সাবজেক্ট স্ট্রিং এর শেষ থেকে সুরু করতে হবে )

আমরা যদি এমন একটি প্যাটার্ন মেচ করাতে চাই যার শেষ অংশ অবশ্যই মেচ করতে হবে কিন্তু সেখানে কোনো ডট থাকতে পারবেনা এবং তার আগে একটি ডট থাকবে এবং তার আগে ডট ছাড়া ক্যারেক্টার
থাকবে।

// get last two segments of host name
$host = "www.php.net";
preg_match_all('/[^.]+\.[^.]+$/', $host, $matches);
print_r($matches);

/*
Array
(
    [0] => Array
        (
            [0] => php.net
        )

)

How to Pass Zend PHP 5.3 exam in first attempt?

Some of the predefined POSIX in regular expression

The usage position of metacharacters in a regular expression determines the result of the regular expression. If caret (^) metacharacter is used inside a character list, it means the negation of a character list. Therefore, [^[:digit:]] looks for a pattern consisting of any non-digit character. Therefore, in the given scenario, you will use the [^[:digit:]] regular expression to accomplish the task.

Some of the predefined POSIX (Portable Operating System Interface) character classes are as follows:
  • [:alpha:] Alphabetic characters
  • [:lower:] Lower case alphabetic characters
  • [:upper:] Upper case alphabetic characters
  • [:digit:] Numeric digits
  • [:alnum:] Alphanumeric characters
  • [:space:] Non-printing space characters
  • [:punct:] Punctuation characters
  • [:print:] Printable characters
Answer options A and D are incorrect. The caret (^) metacharacter cannot be used at the end of any regular expression.

Pattern = [^[:digit:]]

Difference between greedy and ungreedy

 Greedy এর ক্ষেত্রে :
প্রথম প্যাটার্ন পরবর্তী কোনো প্যাটার্ন কে বার বার মেচ করার সূযুগ না দিয়ে প্রথম প্যাটার্ন এগিয়ে চলবে, পরবর্তী প্যাটার্ন কে সুধু শেষ বার সুযুগ দেবে। অর্থাৎ জুর যার মুল্লুক তার।

preg_match_all('/.*day/', "saturdaysunday", $matches);
print_r($matches);
 
Output: 
Array
(
    [0] => Array
        (
            [0] => saturdaysunday
        )
)



Un-Greedy এর ক্ষেত্রে :
 প্রথম প্যাটার্ন পরবর্তী কোনো প্যাটার্ন কে বার বার মেচ করার সূযুগ  দিবে, প্রথম প্যাটার্ন এগিয়ে চলবে।
preg_match_all('/.*?day/', "saturdaysunday", $matches);
// OR preg_match_all('/.*day/U', "saturdaysunday", $matches);
print_r($matches);

Output:
Array
(
    [0] => Array
        (
            [0] => saturday
            [1] => sunday
        )
)

Sunday, 20 March 2016

Subpattern in regular expression

টোটাল প্যাটার্ন যদি ম্যাচ করে তাহলে সেই টোটাল প্যাটার্ন এবং সাব প্যাটার্ন গুলি এরে তে রিটার্ন। যদি টোটাল প্যাটার্ন এ একটাই সাব প্যাটার্ন থাকে তাহলে একটা এম্পটি স্ট্রিং ধরে টোটাল প্যাটার্ন করে এবং সেই টোটাল প্যাটার্ন এবং সাব প্যাটার্ন গুলি এরে তে রিটার্ন করে। টোটাল প্যাটার্ন যদি  ম্যাচ না করে তাহলে সাব প্যাটার্ন ও রিটার্ন করেনা।

preg_match('/saturday(sunday)/', "saturdaysunday", $matches);
print_r($matches);

/* Using subpattern (sunday)
Array
(
    [0] => saturdaysunday
    [1] => sunday
)
*/

Saturday, 19 March 2016

Non greedy/ungreedy regular expression

বাই ডিফল্ট রেগুলার এক্সপ্রেশন হয় Greedy, অর্থাৎ quantifier (.*, অন্যান্য) যত character পায় ততই consume করে যেমন xxxxzzzz, এখানে ৪ টা x এবং ৪ টা z, এখানে আমি যদি (.*)  ব্যবহার করি এটা সবগুলি character
নিয়া নিবে, যেমন এই প্যাটার্ন = "/(.*)(z+)/" সবগুলি নিতে চায় তবে যেহেতু z+ পরে ব্যবহার করা হইয়াছে তাই বেচারা z+ জন্য একটা z রেখে সবগুলু x এবং z নিয়া নেয়। তবে ইন্টারেষ্টিং হলো এখানে যদি z* ব্যবহার করা হত .*  সবগুলি character নিয়ে নিত।

<?php
/*** 4 x and 4 z chars ***/
$string = "xxxxzzzz";
/*** greedy regex ***/
preg_match("/^(.*)(z+)$/",$string,$matches);
/*** results ***/
echo $matches[1];
echo "<br />";
echo $matches[2];
?>

Friday, 18 March 2016

Look Aheads, Look Behinds regular expression


http://infoheap.com/php-look-ahead-look-behind-regex/

//Negative look ahead

//Return true if string1(hello) is not followed by string2( world)
ট্রু রিটার্ন করে যদি একটা স্ট্রিং এর পরে আরেকটা স্ট্রিং না থাকে।
যেমন hello এর পরে যদি  wold না থেকে অন্য কিছু থাকলে তবে এটি match করবে। 
(এক্ষেত্রে ওয়ার্ল্ড এর আগে একটি স্পেস আছে) 
if (preg_match('/hello(?! world)/i', "hello something else", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}



//Positive look ahead

//Return true if string1(hello) is followed by string2( world)

if (preg_match('/hello(?= world)/i', "hello world", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}





//Negative look behind

//Return true if string2(world) is not preceded by string1(hello )
if (preg_match('/(?<!hello )world/i', "something world", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}



//Positive look behind

//Return true if string2(world) is preceded by string1(hello )

if (preg_match('/(?<=hello )world/i', "hello world", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}

Wednesday, 16 March 2016

substr_compare() : compares main_str from position offset with sub_str up to length characters.

echo substr_compare("abc", "abc", 0); // 0, similar to strcmp
echo substr_compare("bbc", "abc", 0); // 1, similar to strcmp
echo substr_compare("abcd", "abc", 0); // 1, similar to strcmp
echo substr_compare("abc", "abcd", 0); // -1, similar to strcmp
echo substr_compare("abc", "bbc", 0); // -1, similar to strcmp
//If length is specified, that specified length of substr and mainstr is compared, the other chars are ignored
echo substr_compare("abc", "abcd", 0 , 3); // 0
//If specified length is more than the subsring but subsring is matched with the part of the
//mainstr, so ramining length of subsring is printed
echo substr_compare("abcdefgh", "abc", 0 , 6); // 3
\http://www.w3schools.com/php/func_string_substr_compare.asp
offset theke suru kore length porjonto main string er sathe subsring er tulona kora hoi.

<?phpecho substr_compare("abcde""bc"12); // 0echo substr_compare("abcde""de", -22); // 0echo substr_compare("abcde""bcg"12); // 0echo substr_compare("abcde""BC"12true); // 0echo substr_compare("abcde""bc"13); // 1
//echo substr_compare("abcde""cd"12); // -1
// cd ar offset deo offset chea basiecho substr_compare("abcde""abc"51); // warning?>

strcspn : Returns the length of the initial segment of subject which does not contain any of the characters in mask.

int strcspn ( string $subject , string $mask [, int $start [, int $length ]] )
Mask এর যে কোন একটা character মিললে তার আগ পর্যন্ত length রিটার্ন করে।
<?php
$a 
strcspn('abcd',  'apple');

$b strcspn('abcd',  'banana');
$c strcspn('hello''l'); 
$d strcspn('hello''world'); 
$e strcspn('abcdhelloabcd''abcd', -9);
$f strcspn('abcdhelloabcd''abcd', -9, -5);

var_dump($a);var_dump($b);var_dump($c);

var_dump($d);var_dump($e);var_dump($f); 
?>
int(0)
int(0)
int(2)
int(2)
int(5)
int(4)
 

Monday, 14 March 2016

chr and ord in respect of printf, sprintf

echo chr("65"); // A
printf("%c", "65"); //A
echo sprintf("%c", "65"); //A

echo ord("A"); // 65

bin2hex and hex2bin

bin2hex — Convert binary data into hexadecimal representation,
here BINARY means ASCII characters

$b = "Aa";
echo bin2hex($b); // 4161 , 41=A, 61=B
echo hex2bin("4161"); // Aa

addcslashes

string addcslashes ( string $str , string $charlist )
Returns a string with backslashes before characters that are listed in charlist parameter.

charlist
1) \n and \r are converted to C-style
2) 0-32 and higher than 126 converted to octal
3) A..z the range is correct, A to Z, a to z and period will be escaped
4) z..A the range is incorrect, only z,A and period(.) will be escaped
5) "\0..\37", which would escape all characters with ASCII code between 0 and 31.

echo addcslashes('foo[ ]', 'A..z'); // \f\o\o\[ \]

echo addcslashes("zoo['.']", 'z..A'); // \zoo['\.']

addslashes

addslashes escape
1) ' (single quote)
2) " (double quote)
3) \ (slash)
4) NULL byte

Which of the following global parameters was auto addslashes when magic_quote_gpc was on in PHP 5.4? (choose 3)

1. $_GET
2. $_POST
3. $_COOKIE
4. $_SERVER




Sunday, 13 March 2016

sprintf

echo sprintf("%'x8.1f", 18); // xxxx18.0, total 8 characters, .1f after point one 0 be padded, if 18.1 no 0 be padded, 'x8 means output be 8 chars, if number is 2 digit, the remaining chars be padded with 'x and after point 0 be padded.

echo $formatted = sprintf("%01.4f", .35);  // 0.3500, one 0 padded in left and 4 zero padded in right, if digits replace the zero places no zero will be shown.



echo sprintf("%10.2f", 1); // default padding space
space
space
space
space
space
space
1
.
0
0

echo sprintf("%10.2f", .1); // .1 = 0.1
space
space
space
space
space
space
0
.
1
0

echo sprintf("%010.2f", .1); // no need single quote for zero
0
0
0
0
0
0
0
.
1
0

echo sprintf("%'z10.2f", .1); // single quote needed for all except zero
z
z
z
z
z
z
0
.
1
0

$x = 10;
$y = -10;
echo sprintf("%+d", $x);
echo sprintf("%+d", $y);

printf

echo printf("%s", "XXXX"); // XXXX4, Returns the length of the outputted string

<?php
$intChar = 65;
printf('%c', $intChar); // A

Friday, 11 March 2016

Difference among intersect functions

1. array_intersect 
শুধু data চেক করে, index চেক করেনা


2. array_uintersect 
data চেক করে user defined function এর মধমে, index চেক করেনা

3. array_uintersect_assoc
data চেক করে user defined function এর মধমে, index চেক করে

4. array_intersect_uassoc
 data চেক করে, index চেক করে user defined function এর মধমে

5. array_uintersect_uassoc
data চেক করে user defined function এর মধমে, index চেক করে user defined function এর মধমে 

Saturday, 5 March 2016

Difference among Sort, SORT_NATURAL, SORT_FLAG_CASE

asort($array1,SORT_NATURAL) == natsort($array1) == uasort($array1, "strnatcmp");

asort($array1,SORT_NATURAL | SORT_FLAG_CASE) == natcasesort($array1) == uasort($array1, "strnatcasecmp");

$array1 = array("img12.png", "img10.png", "img2.png", "img1.png");

sort($array1);
echo "Standard sorting\n";
print_r($array1);

sort($array1,SORT_NATURAL);
echo "\nNatural order sorting\n";
print_r($array1);

$array1 = array("img12.png", "img10.png", "Img2.png", "img1.png");

sort($array1);
echo "Standard sorting\n";
print_r($array1);

sort($array1,SORT_NATURAL); // like natsort, but index not preserved.
echo "\nNatural order sorting\n";
print_r($array1);

sort($array1,SORT_NATURAL | SORT_FLAG_CASE); like natcasesort, but index not preserved.
echo "\nNatural order sorting, case insensitive\n";
print_r($array1);

Friday, 4 March 2016

Array Specials

<?php
echo "<pre>";
$array = array ('3' => 'a', 3 => 'b', 3.5=>"c", "3.5"=>"d", -3=>"e", -3.5=>"f", "-3"=>"g", "-3.5"=>"h");
print_r($array);
?>

Array
(
    [3] => c
    [3.5] => d
    [-3] => g
    [-3.5] => h
)
 
$array = array (true => 'a', 1 => 'b', "1" => 'c');
var_dump ($array); //c

$array = array (true => 'a', 1 => 'b');
var_dump ($aray); //wrong variable, NULL


$array = array ("" => 'a', null => 'b');
var_dump ($array); //b, NULL converted to emptry string