Skip to content

Instantly share code, notes, and snippets.

@liuxd
Last active November 9, 2018 01:20
Show Gist options
  • Save liuxd/599fa0d6137316d36d7500a29acfebf9 to your computer and use it in GitHub Desktop.
Save liuxd/599fa0d6137316d36d7500a29acfebf9 to your computer and use it in GitHub Desktop.
[PHP] #Tips

{} for String

$a = 'abc';
echo $a{0}; // Output: a
echo $a{1}; // Output: b

How to check if a string's length is enough?

$str = 'abcd';

if (isset($str{3})) {
    echo "enough";
}

Splendid Regular Expression?

$pattern = '/<a href=\".*\">.*<\/a>/'; // ugly!
$pattern = '#<a href=".*">.*</a>#'; // wonderful!

A big array to check.

# Usually
$arr = ['tom', 'jerry', 'peter'];

if (in_array($v, $arr)) {
    return true;
} else {
    return false;
}

# Better
$arr = ['tom', 'jerry', 'peter'];
$arr_handled = array_flip($arr);

if (isset($arr_handled[$v])) {
    return true;
} else {
    return false;
}

Tranverse alphabet.

$start = 'a';

for ($n = 0;$n < 26;$n++) {
    echo $start;
    $start++;
}

Time limit in CLI mode

In command line mode in PHP, max_execution_time is 0 as default, whatever the value in php.ini.

You can set time limit with two methods below:

  • set_time_limit(3)
  • ini_set('max_execution_time', 1)

Caution:

Both set_time_limit(...) and ini_set('max_execution_time',...); won't count the time cost of sleep,file_get_contents,shell_exec,mysql_query etc. Use for(;;); is a good idea.

Remove EOF in the string

$sNoEndOfLine = str_replace(PHP_EOL, "", $sString);

Get the unixtime of next month

strtotime(date('Y-m') . '+1 month');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment