Home Backend Development PHP Tutorial PHP common function collection (1)_PHP tutorial

PHP common function collection (1)_PHP tutorial

Jul 13, 2016 pm 05:49 PM
php string one function at string Commonly used collect array of return

/**
* Returns the string or array processed by addslashes
* @param $string The string or array to be processed
* @return mixed
​*/
 function new_addslashes($string){
     if(!is_array($string)) return addslashes($string);
     foreach($string as $key => $val) $string[$key] = new_addslashes($val);
     return $string;
 }
 
 /**
* Return the string or array processed by stripslashes
* @param $string The string or array to be processed
* @return mixed
​*/
 function new_stripslashes($string) {
     if(!is_array($string)) return stripslashes($string);
     foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
     return $string;
 }
 
 /**
* Returns the string or array processed by addslashe
* @param $obj The string or array to be processed www.2cto.com
* @return mixed
​*/
 function new_html_special_chars($string) {
     if(!is_array($string)) return htmlspecialchars($string);
     foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
     return $string;
 }
 /**
* Security filter function
*
* @param $string
* @return string
​*/
 function safe_replace($string) {
     $string = str_replace('%20','',$string);
     $string = str_replace('%27','',$string);
     $string = str_replace('%2527','',$string);
     $string = str_replace('*','',$string);
     $string = str_replace('"','"',$string);
     $string = str_replace("'",'',$string);
     $string = str_replace('"','',$string);
     $string = str_replace(';','',$string);
     $string = str_replace('<','<',$string);
     $string = str_replace('>','>',$string);
     $string = str_replace("{",'',$string);
     $string = str_replace('}','',$string);
     return $string;
 }
 
 
 
 /**
* Filter control characters with ASCII codes from 0-28
* @return String
​*/
 function trim_unsafe_control_chars($str) {
     $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
     return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
 }
 
 /**
* Format text field content
*
* @param $string text field content
* @return string
​*/
 function trim_textarea($string) {
     $string = nl2br ( str_replace ( ' ', ' ', $string ) );
     return $string;
 }
 
 /**
* Format the text into a string suitable for js output
* @param string $string The string to be processed
* @param intval $isjs Whether to perform string formatting, the default is to perform
* @return string processed string
​*/
 function format_js($string, $isjs = 1)
 {
     $string = addslashes(str_replace(array("r", "n"), array('', ''), $string));
     return $isjs ? 'document.write("'.$string.'");' : $string;
 }
 
 /**
* Escape javascript code tag
*
* @param $str
* @return mixed
​*/
 function trim_script($str) {
     $str = preg_replace ( '/<([/]?)script([^>]*?)>/si', '<\1script\2>', $str );
     $str = preg_replace ( '/<([/]?)iframe([^>]*?)>/si', '<\1iframe\2>', $str );
     $str = preg_replace ( '/<([/]?)frame([^>]*?)>/si', '<\1frame\2>', $str );
     $str = preg_replace ( '/]]>/si', ']] >', $str );
     return $str;
 }
 /**
* Get the complete URL address of the current page
​*/
 function get_url() {
     $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
     $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
     $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
     $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
     return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
 }
 /**
* Character interception supports UTF8/GBK
* @param $string
* @param $length
* @param $dot
​*/
 function str_cut($string, $length, $dot = '...') {
     $strlen = strlen($string);
     if($strlen <= $length) return $string;
     $string = str_replace(array(' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
     $strcut = '';
     if(strtolower(CHARSET) == 'utf-8') {
         $length = intval($length-strlen($dot)-$length/3);
         $n = $tn = $noc = 0;
         while($n < strlen($string)) {
             $t = ord($string[$n]);
             if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                 $tn = 1; $n++; $noc++;
             } elseif(194 <= $t && $t <= 223) {
                 $tn = 2; $n += 2; $noc += 2;
             } elseif(224 <= $t && $t <= 239) {
                 $tn = 3; $n += 3; $noc += 2;
             } elseif(240 <= $t && $t <= 247) {
                 $tn = 4; $n += 4; $noc += 2;
             } elseif(248 <= $t && $t <= 251) {
                 $tn = 5; $n += 5; $noc += 2;
             } elseif($t == 252 || $t == 253) {
                 $tn = 6; $n += 6; $noc += 2;
             } else {
                 $n++;
             }
             if($noc >= $length) {
                 break;
             }
         }
         if($noc > $length) {
             $n -= $tn;
         }
         $strcut = substr($string, 0, $n);
         $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);
     } else {
         $dotlen = strlen($dot);
         $maxi = $length - $dotlen - 1;
         $current_str = '';
         $search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
         $replace_arr = array('&',' ', '"', ''', '“', '”', '—', '<', '>', '·', '…',' ');
         $search_flip = array_flip($search_arr);
         for ($i = 0; $i < $maxi; $i++) {
             $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
             if (in_array($current_str, $search_arr)) {
                 $key = $search_flip[$current_str];
                 $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
             }
             $strcut .= $current_str;
         }
     }
     return $strcut.$dot;
 }
  
 
 
 /**
* Get request ip
*
* @return ip address
​*/
 function ip() {
     if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
         $ip = getenv('HTTP_CLIENT_IP');
     } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
         $ip = getenv('HTTP_X_FORWARDED_FOR');
     } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
         $ip = getenv('REMOTE_ADDR');
     } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
         $ip = $_SERVER['REMOTE_ADDR'];
     }
     return preg_match ( '/[d.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
 }
 
 function get_cost_time() {
     $microtime = microtime ( TRUE );
     return $microtime - SYS_START_TIME;
 }
 /**
*Program execution time
*
* @return int unit ms
​*/
 function execute_time() {
     $stime = explode ( ' ', SYS_START_TIME );
     $etime = explode ( ' ', microtime () );
     return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
 }
 
 /**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ,默认为0123456789
 * @return   string     字符串
 */
 function random($length, $chars = '0123456789') {
     $hash = '';
     $max = strlen($chars) - 1;
     for($i = 0; $i < $length; $i++) {
         $hash .= $chars[mt_rand(0, $max)];
     }
     return $hash;
 }
 
 /**
* Convert string to array
*
* @param string $data string
* @return array Returns the array format. If data is empty, an empty array is returned
​*/
 function string2array($data) {
     if($data == '') return array();
     eval("$array = $data;");
     return $array;
 }
 /**
* Convert array to string
*
* @param array $data Array
* @param bool $isformdata If it is 0, new_stripslashes processing is not used, optional parameter, default is 1
* @return string Returns a string. If data is empty, it returns empty
​*/
 function array2string($data, $isformdata = 1) {
     if($data == '') return '';
     if($isformdata) $data = new_stripslashes($data);
     return addslashes(var_export($data, TRUE));
 }
 
 /**
* Convert the number of bytes to other units
*
*
* @param string $filesize byte size
* @return string Return size
​*/
 function sizecount($filesize) {
     if ($filesize >= 1073741824) {
         $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
     } elseif ($filesize >= 1048576) {
         $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
     } elseif($filesize >= 1024) {
         $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
     } else {
         $filesize = $filesize.' Bytes';
     }
     return $filesize;
 }
 /**
* String encryption and decryption functions
*
*
* @param string $txt String
* @param string $operation ENCODE is encryption, DECODE is decryption, optional parameters, the default is ENCODE,
* @param string $key Key: numbers, letters, underscore
* @return string
​*/
 function sys_auth($txt, $operation = 'ENCODE', $key = '') {
     $key    = $key ? $key : pc_base::load_config('system', 'auth_key');
     $txt    = $operation == 'ENCODE' ? (string)$txt : base64_decode($txt);
     $len    = strlen($key);
     $code   = '';
     for($i=0; $i          $k      = $i % $len;
         $code  .= $txt[$i] ^ $key[$k];
     }
     $code = $operation == 'DECODE' ? $code : base64_encode($code);
     return $code;
 }
 
 /**
 * 语言文件处理
 *
 * @param    string      $language   标示符
* @param array $pars Escaped array, two-dimensional array, 'key1'=>'value1', 'key2'=>'value2',
* @param string $modules Multiple modules are separated by half-width commas, such as: member,guestbook
* @return string Language character
*/
function L($language = 'no_language',$pars = array(), $modules = '') {
      static $LANG = array();
      static $LANG_MODULES = array();
      static $lang = '';
If(defined('IN_ADMIN')) {
$lang = SYS_STYLE ? SYS_STYLE : 'zh-cn';
} else {
            $lang = pc_base::load_config('system','lang');
}
If(!$LANG) {
require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
If(defined('IN_ADMIN')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
if(file_exists(PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
}
If(!emptyempty($modules)) {
          $modules = explode(',',$modules);
           foreach($modules AS $m) {
If(!isset($LANG_MODULES[$m])) require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
         }
}
If(!array_key_exists($language,$LANG)) {
            return $LANG['no_language'].'['.$language.']';
} else {
           $language = $LANG[$language];
            if($pars) {
foreach($pars AS $_k=>$_v) {
                      $language = str_replace('{'.$_k.'}',$_v,$language);
            }
         }
           return $language;
}
}

/**
* Template call
*
* @param $module
* @param $template
* @param $istag
* @return unknown_type
​*/
function template($module = 'content', $template = 'index', $style = '') {
       
If(strpos($module, 'plugin/')!== false) {
            $plugin = str_replace('plugin/', '', $module);
             return p_template($plugin, $template,$style);
}
$module = str_replace('/', DIRECTORY_SEPARATOR, $module);
If(!emptyempty($style) && preg_match('/([a-z0-9-_]+)/is',$style)) {
} elseif (emptyempty($style) && !defined('STYLE')) {
If(defined('SITEID')) {
$siteid = SITEID;
          } else {
                $siteid = param::get_cookie('siteid');
         }
              if (!$siteid) $siteid = 1;
          $sitelist = getcache('sitelist','commons');
         if(!emptyempty($siteid)) {
             $style = $sitelist[$siteid]['default_style'];
         }
     } elseif (emptyempty($style) && defined('STYLE')) {
         $style = STYLE;
     } else {
         $style = 'default';
     }
     if(!$style) $style = 'default';
     $template_cache = pc_base::load_sys_class('template_cache');
     $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
     if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
         if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {    
             $template_cache->template_compile($module, $template, $style);
         }
     } else {
         $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
         if(!file_exists($compiledtplfile) || (file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
             $template_cache->template_compile($module, $template, 'default');
         } elseif (!file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
             showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
         }
     }
     return $compiledtplfile;
 }
 
 /**
* Output custom errors
*
* @param $errno error number
* @param $errstr Error description
* @param $errfile error file address
* @param $errline Error line number
* @return string error message
​*/
 
 function my_error_handler($errno, $errstr, $errfile, $errline) {
     if($errno==8) return '';
     $errfile = str_replace(PHPCMS_PATH,'',$errfile);
     if(pc_base::load_config('system','errorlog')) {
         error_log(''.date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."rn", 3, CACHE_PATH.'error_log.php');
     } else {
         $str = '

errorno:' . $errno . ',str:' . $errstr . ',file:' . $errfile . ',line' . $errline .'
Need Help?
';
         echo $str;
     }
 }
 
 /**
* The prompt information page jumps. If the jump address is passed in an array, the page will prompt multiple addresses for the user to choose. The default jump address is the first value of the array and the time is 5 seconds.
* showmessage('Login successful', array('Default jump address'=>'http://www.phpcms.cn'));
* @param string $msg Prompt message
* @param mixed(string/array) $url_forward jump address
* @param int $ms Jump waiting time
​*/
 function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
     if(defined('IN_ADMIN')) {
         include(admin::admin_tpl('showmessage', 'admin'));
     } else {
         include(template('content', 'message'));
     }
     exit;
 }
 /**
* Query whether a character exists in a certain string
*
* @param $haystack string
* @param $needle The character to find
* @return bool
​*/
 function str_exists($haystack, $needle)
 {
     return !(strpos($haystack, $needle) === FALSE);
 }
 
 /**
* Get file extension
*
* @param $filename file name
* @return extension
​*/
 function fileext($filename) {
     return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
 }
 
 /**
* Load template tag cache
* @param string $name cache name
* @param integer $times cache time
​*/
 function tpl_cache($name,$times = 0) {
     $filepath = 'tpl_data';
     $info = getcacheinfo($name, $filepath);
     if (SYS_TIME - $info['filemtime'] >= $times) {
         return false;
     } else {
         return getcache($name,$filepath);
     }
 }
 
 /**
* Write cache, the default is file cache, no cache configuration is loaded.
* @param $name cache name
* @param $data cache data
* @param $filepath data path (module name) caches/cache_$filepath/
* @param $type cache type [file,memcache,apc]
* @param $config configuration name
* @param $timeout expiration time
​*/
 function setcache($name, $data, $filepath='', $type='file', $config='', $timeout=0) {
     pc_base::load_sys_class('cache_factory','',0);
     if($config) {
         $cacheconfig = pc_base::load_config('cache');
         $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
     } else {
         $cache = cache_factory::get_instance()->get_cache($type);
     }
 
     return $cache->set($name, $data, $timeout, '', $filepath);
 }
 
 /**
* Read cache, the default is file cache, no cache configuration is loaded.
* @param string $name cache name
* @param $filepath data path (module name) caches/cache_$filepath/
* @param string $config configuration name
​*/
 function getcache($name, $filepath='', $type='file', $config='') {
     pc_base::load_sys_class('cache_factory','',0);
     if($config) {
         $cacheconfig = pc_base::load_config('cache');
         $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
     } else {
         $cache = cache_factory::get_instance()->get_cache($type);
     }
     return $cache->get($name, '', '', $filepath);
 }
 
 /**
* Delete the cache, which defaults to file cache and does not load the cache configuration.
* @param $name cache name
* @param $filepath data path (module name) caches/cache_$filepath/
* @param $type cache type [file,memcache,apc]
* @param $config configuration name
​*/
 function delcache($name, $filepath='', $type='file', $config='') {
     pc_base::load_sys_class('cache_factory','',0);
     if($config) {
         $cacheconfig = pc_base::load_config('cache');
         $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
     } else {
         $cache = cache_factory::get_instance()->get_cache($type);
     }
     return $cache->delete($name, '', '', $filepath);
 }
 
 摘自chaojie2009的专栏

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478386.htmlTechArticle/*** Return the string or array processed by addslashes * @param $string The string or array to be processed * @return mixed*/ function new_addslashes($string){ if(!is_array($string)...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles