search
HomeBackend DevelopmentPHP TutorialPHP common functions and common troubleshooting questions_PHP tutorial

首先介绍下比较简单但必不可少且实用的知识,可以当手册查询,适合像我一样的新手看。

PHP常用库函数介绍

一、PHP字符串操作常用函数
1.确定字符串长度
int strlen(string str)
2.比较两个字符串
a. strcmp函数对两个字符串进行二进制安全的比较,并区分大小写
int strcmp(string str1,string str2)
b. 以不区分大小写的方式比较两个字符串
int strcasecmp(string str1,string str2)

3.求两个字符串相同部分
int strspn(string str1,string str2)
4.求两个字符串的不同部分
5.int strcspn(string str1,string str2)
6.处理字符串大小写
a. 将字符串全部转换为小写
string strtolower(string str)
b. 将字符串全部转化为大写
string strtoupper(string str)
c. 将字符串第一个字符大写
string ucfirst(string str)
d. 把字符串中每个单词的首字符转换为大写
string ucwords(string str)
7.字符串与HTML相互转换
a. 将换行符转换为HTML终止标记
string bl2br(string str)
b. 将特殊字符转换wieldHTML等价形式(不解析格式)
string htmlentities(string str[,int quote_style[,int charset]])
string htmlspecialchars(string str[,int quote_style[,string charset]])
c. 将HTML转换为纯文本,移除所有的php和html标签
string strip_tags(string str[,string allowable_tags])
d. 将文本转换为HTML等价形式
array get_html_translaction_table(int table[,int quote_style])
e. 创建一个自定义的转换清单
string strtr(string str,array replacements)
8.正则表达式函数的替代函数
a. strtok函数根据预定义的字符串列表来解析字符串
string strtok(string str,string tokens):返回直到遇到tokens之前的所有内容
b. 根据预定义的定界符分析字符串
array explode(string separator,string str[,int limit]):分割字符串
c. 将数组转换为字符串
string implode(string delimiter, array array)
d. 找到字符串的第一次出现
int strpos(string str,string substr[,int offset])
e. 找到字符串的最后一次出现
int strrpos(string str,char substr[,offset])
f. 用另外一个字符串替代字符串的所有实例
mixed str_replace(string occurrence,mixed replacement,mixed str[,int count])
g. 获取字符串的一部分strstr返回字符串中预定义字符串第一次出现开始的剩余部分
string strstr(string str,string occurrence)
h. 根据预定义的偏移返回字符串一部分
string substr(string str,int start[,ing length]):start可为负数,表示倒数第几开始
i. 确定字符串出现的频率
int substr_count(string str,string substring)
j. 用另一个字符串替换一个字符串的一部分
string substr_replace(string str,string replacement,int start[,int length])
9.填充和剔除字符串
a. 从字符串开始出裁剪字符
string ltrim(string str[,string charliset])
b. 从字符串结尾裁剪字符
string rtrim(string str[,string charliset])
c. 从字符串两端裁剪字符
string trim(string str[,string charliset])
d. 填充字符串
string str_pad(string str,int length[,string pad_string[,int pad_type]])
10.字符和单词计数
a. 字符串中字符计数
mixed count_chars(string str[,mode])
b. 字符串中单词总数计数
mixed str_word_count(string str[,int format])
二、PHP Web开发中常用的三个表单验证函数

(1)isset();——适合于检测是否存在这个参数。用来避免引用不存在的变量

定义和作用范围:用于测试一个变量是否具有值(包括0,FALSE,或者一个空字串都返回true,但不能是NULL),即:“http://localhost/?fo=”也是可以通过检测,因此不适用。但如果是“http://localhost/”参数中并不含fo参数,就可以用isset来检测,此时isset($_GET['fo'])返回false

不适用于:该函数不适合于验证html表单中的文本的有效方式。要检查用户输入文本是否有效,可以用empty();

(2)empty();——最好用的一个函数,用于检查变量是否具有空值

 定义和作用范围:用于检查变量是否具有空值:包括:空字串,0,null 或false,这些都返回false,即:“http://localhost/?fo=”或“http://localhost/?fo=0”时,empty检测出来的结果都是ture

不适用范围:不适用于检测可为0的参数

(3)is_numeric();——检查变量是否为数字

定义和作用范围:检查变量是否为数字,只适用于检测数字

不适用范围:但假如参数名不存在,会出错,因此不适合于第一层检测

Another useful verification function is checkdate(month, day, $year), which is used to confirm whether a certain date exists or existed in the past

Comprehensive example:

This is the form:

Copy the code The code is as follows:





< ;title>Form validation example




Pass a valid value Pass an empty value Pass 0 Value



Gender: Male Gender: Female



Clear





[code]
This is verification
[code] ini_set("display_errors",1);
//ini_set("error_reporting",E_ALL); print_r
error_reporting(E_ALL);

$a=NULL;
if(isset($a))echo 'isset of variable $a is true';

echo '

isset situation:

';
if( isset($_GET['fo'])){
echo 'The isset of variable 'fo' is true, the variable is available';
}else{
echo 'The isset of variable 'fo' is false, No variable setting';
}

echo '

empty situation:

';
if(empty($_GET['fo'])){
echo 'The empty value of the variable 'fo' is true, that is, a null value or an invalid value';
}else{
echo 'The empty value of the variable 'fo' is false, and it has a value';
}

echo '

is_numeric case:

';
if(is_numeric($_GET['fo'])){ //When there is no fo parameter in the parameter, then Something went wrong.
echo 'is_numeric of variable 'fo' is true and is a number';
}else{
echo 'is_numeric of variable 'fo' is false and is not a number';
}

echo "

$_GET['fo']='' situation:

";
if($_GET['fo']==''){ //In the parameters If there is no fo parameter, an error occurs.
echo 'fo has no value, an empty string';
}elseif($_GET['fo']!=''){
echo 'fo has a value, not ''.';
}

echo "

$_GET['sex']='m' case:

";
if($_GET['sex']= ='m'){ //An error occurs when there is no sex variable in the parameter.
echo 'male';
}elseif($_GET['sex']=='f'){
echo 'female';
}
?>

3. Other commonly used library functions

(1) ini_set ini_get - List of operable configuration parameters
In order to make our programs have better compatibility on different platforms, many times we have to obtain the current Php operating environment parameters.
For example, what we often use:
Get the magic_quotes_gpc status to decide whether we escape (addslashes) the data when the form is submitted;
Set max_execution_time to extend the execution time of the program;
Set error_reporting Make your project switch between the development and operation phases;
Set memory_limit to increase memory, etc...
(2) ini_set(string varname, string newvalue): //Set the parameters of the environment configuration
ini_get (string varname) : //Get the parameters of the environment configuration
The PHP ini_set function is to set the value in the option. It takes effect after the function is executed. When the script ends, this setting also becomes invalid. Not all options can be set by the function. For specific values

Statement
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version