Home Backend Development PHP Tutorial 基于PHP常用字符串的总结(待续)_php技巧

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

May 17, 2016 am 09:02 AM
php string

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

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
4 weeks 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