Home php教程 php手册 基于PHP常用字符串的总结(待续)

基于PHP常用字符串的总结(待续)

Jun 13, 2016 am 11:49 AM
array echo em implode php and Split merge based on string Commonly used Summarize of

1.分割与合并
implode:
echo implode(",", array('lastname', 'email', 'phone'));//数组转成字符串

explode:
print_r(explode(",", 'lastname,email,phone'));//字符串转成数组

split:
print_r(split("[/.-]","2008-9.12"));//以/或.或-任一符号切成数组

str_split:
print_r(str_split("Hello Friend",1));//将字符串切开

preg_split:
//正则分割
//$ops = preg_split("{[+*/-]}","3+5*9/2");
//print_r($ops);//返回:Array ( [0] => 3 [1] => 5 [2] => 9 [3] => 2 )

http_build_query:
//生成 url-encoded 之后的请求字符串
$data = array('localhost'=>'aa',
'user'=>'bb',
'password'=>'cc');
echo http_build_query($data);//返回:localhost=aa&user=bb&password=cc

strtok:
//将字符串切成小段
$string = "This is\tan example\nstring";
echo strtok($string,"\n\t");//返回:This is
echo '


';
echo strtok("\n\t"); //当第二次返回:an example
echo '
';
echo strtok("\n\t"); //当第三次返回:string
2.查找和替换
字符串中很多是 r:取最后的,i:不区分大小写的
echo $pos = strpos('abcdef abcdaef', 'a'); // 字母a第一次出现的位置,区分大小写
echo $pos = strrpos('abcdef abcdeaf', 'a'); // 字母a最后一次出现的位置,区分大小写
stripos:不区分大小写
strripos:不区分大小写
echo strstr('user@exa@mple.com', '@');//返回:@exa@mple.com
stristr:不区分大小写
echo strchr('user@exa@mple.com', '@');//返回:@exa@mple.com
strrchr:则返回:@mple.com,

preg_grep:
//返回与模式匹配的数组单元
$food = preg_grep("/^p/",array("apple","orange","pip","banana"));
print_r($food); //返回:Array ( [2] => pip )

strtr:
//以指定的数组替换找到的字符串
$arr = array("www"=>"ftp","yahoo"=>"baidu");
echo strtr("www.yahoo.com",$arr);//返回:ftp.baidu.com
echo strtr("www.yahoo.com","wo","sx");//返回:sss.yahxx.cxm 翻译字符串 把所有w换成了s把所有的o换成了x

strspn:
//找出比对到的最初部份的长度
echo strspn("abcdefg","1234567890");//返回:0
//找出没有比对到的最初部份的长度
echo strcspn("abcdefg","1234567890");//返回:7


3.正则
preg_match:
//返回 pattern 所匹配的次数。要么是 0 次(没有匹配)或 1 次,因为 preg_match() 在第一次匹配之后将停止搜索。
if (preg_match ("/php/i", "PhP is the web scripting language of choice."))
echo "存在";
else
echo "不存在";

preg_match_all:
//则相反,会一直搜索到 subject 的结尾处。
preg_match_all("/\(?(\d{3})?\)?(?(1)[\-\s])\d{3}-\d{4}/x",
"Call 555-1212 or 1-800-555-1212", $phones);
print_r($phones[0]);//取得所有的电话号码

ereg_replace:
//URL 替换为超连接
echo ereg_replace("[[:alpha:]]+://[^[:space:]]+[[:alnum:]/]",
"\\0", '这是百度http://www.baidu.com网站。');
preg_replace:过滤
$search = array ("'<script>]*?>.*?</script>'si",  // 去掉 javascript
"']*?>'si",           // 去掉 HTML 标记
"'([\r\n])[\s]+'",                 // 去掉空白字符
"'&(quot|#34);'i",                 // 替换 HTML 实体
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i",
"'(\d+);'e");                    // 作为 PHP 代码运行
$replace = array ("",
"",
"\\1",
"\"",
"&",
"">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
"chr(\\1)");
echo $text = preg_replace ($search, $replace, 'test<script>alert("adfasdf");</script>');

preg_quote:
//转义正则表达式字符,把每个要加\都加上\,符合正则式。
echo preg_quote('$40 for a g3/400','/');//返回:\$40 for a g3\/400

sql_regcase:
//产生用于不区分大小的匹配的正则表达式

echo sql_regcase("Foo-bar.a"); //返回:[Ff][Oo][Oo]-[Bb][Aa][Rr].[Aa]

4.URL 编码处理函数
urlencode:
echo $str = urlencode('http://www.baidu.com?key=百度');//编码
echo urldecode($str);//解码

rawurlencode:
//百分号(%)后跟两位十六进制数的序列都将被替换成原义字符
//注: rawurldecode() 不会把加号('+')解码为空格,而 urldecode() 可以。
echo $str = rawurlencode('http://www.baidu.com?key=百度');//编码
echo rawurldecode($str);

parse_url:
//解析 URL,返回其组成部分
print_r(parse_url("http://username:password@hostname/path?arg=value#anchor"));

parse_str:
//是将URL解析成变量
$str = "id=1&name=2";
parse_str($str);
echo $name;
//有第二个参数时,把值存到了数组中
$str = "id=1&name=2";
parse_str($str,$array);
print_r($array);

5.时间函数
mktime:
//把日期转换成时间戳
echo time()-mktime(0,0,0,9,17,2008);//返回:当前时间和2008年9月17日的时间差。
echo date('Y-m-d H:i:s');//当前的日期和时间

getdate:
//取得日期/时间信息
print_r(getdate(time()));
6.比较
similar_text:
//比较两个字符串的相似度
$a = "Hellohhh6";
$b = "hello3hh";
echo similar_text($a,$b);//返回:6比较对应的位置有多少相同的字符
echo "
";
similar_text($a,$b,$similar);
echo $similar."%"; //输出相同字符的百分比

soundex:
//比较两个单词的发音
$a = "ddHello6";
$b = "hello3";
echo soundex($a)."
";
echo soundex($b)."
";
if(soundex($a)==soundex($b)) echo "发音相同";else echo '不同';

strnatcmp():
//按自然排序法时进行字符串比较
$arr = array("a1.jpg","a2.jpg","a3.jpg","a4.jpg");
$max = $arr[0];
for($i=0;$i{
if(strnatcmp($arr[$i],$max)>0)
$max = $arr[$i];
}
echo $max;//返回:a4.jpg

strcmp:
//区分大小写,按字节进行字符串比较,第一个字符串大于第二个字符串时返回:1,等于返回:0,小于返回:-1
echo strcmp('abc','Abc');
strcasecmp:
//返回两个字符串的相差数
echo strcasecmp('wbc','bbc');//返回:21
strncmp:
//指定字元数目的字符串比对,此函数和相似,不同的是,你可以指定要用来比对的字符串的字元数目。如果任何一个字符串比 len还短时,则会使用那个字符串的长度来比对
echo strncmp("adrdvark","aardwolf",4);//返回:1

7.排序
sort:
//将数组的值由a-z重排
$a = array("1","s","3","n","5");//返回:1,3,5,n,s
sort($a);//排序print_r($a);


8.其他
str_pad:
//填塞字符串成为指定的长度,pad_type可以是STR_PAD_RIGHT、STR_PAD_LEFT或是STR_PAD_BOTH
echo str_pad("www.yahoo.com",17,"_",STR_PAD_BOTH);//字符串的填补函数__www.yahoo.com__
strlen("aaa");//求数组的长度返回:3
strrev();// 字符串的颠倒
strtolower();//转换成小写
strtoupper();//转换成大写
str_replace()将字符串替换,区分大小写str_ireplace()不区分大小写
ucfirst();//将第一个字母转换成大写
ucwords();//将每个单词的第一个字母转换成大写
echo join("&",array('wo', 'men', 'shi'));//字符串的连合 返回:wo&men&shi用&连合

count_chars:
//传回在字符串中使用的字元的资讯
print_r(count_chars("Hellohhh6",0));//返回字符串中每个字节值(0~255)出现的次数作为值的数组。0列出所有的。1只列出现次数大于0的。2只列出现次数等于0的。3返回所使用的字节值组成的字符串。如:6Hehlo。4返回所未使用的字节值组成的字符串
str_replace:
str_replace("yahoo","baidu","www.yahoo.com");
$c = "www.yahoo.com";
$arr = array("yahoo","com");
echo str_replace($arr,"baidu",$c);//返回:www.baidu.baidu

$c = "www.yahoo.com";
$arr1 = array("www","yahoo","com");
$arr2 = array("ftp","baidu","net");
echo str_replace($arr1,$arr2,$c);//返回:ftp.baidu.net

substr($a,2,2);//取子字符串
echo substr_count("This is a test", "is");//统计子字符串的出现的个数
substr_replace();//替换子字符串

$url = "http://localhost/zheng_ze_biao_da/youxiang.php";
echo substr($url,strrpos($url,"/")+1);//返回:youxiang.php用于返回文件名

str_word_count:
$a = "I/ love/ you/";
echo str_word_count($a);//返回:3 统计字符串的单词的个数
print_r(str_word_count($a,1));//返回:Array ( [0] => I [1] => love [2] => you )
//print_r(str_word_count($a,2));//返回:Array ( [0] => I [3] => love [9] => you )
//print_r(str_word_count($a,1,"/"));返回:Array ( [0] => I/ [1] => love/ [2] => you/ )这里是忽略"/"的
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

Video Face Swap

Video Face Swap

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

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)

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles