php字符串是php中一种数据类型了,字符串在程序开发中占着很重的地位,下面我来给php入门者介绍php字符串的一些基于知识与使用说明吧。
输出字符串
在PHP中,有四种方法输出字符串,echo结构可以一次输出多个值;print()只可以输出一个值;printf()可以格式化输出;print_r()可以输出数组,对调试很有好处,下面一一进行介绍。
1.echo
echo 是PHP的一个关键字,它没有返回值,在写法上,它可以省略小括号,实例代码如下:
- echo 'Test String';
- echo('Test String');
2.print
print 也是PHP的一个关键字,它有返回值,一般返回true,返回false的情况应该没有,在写法上,它和echo一样,可以省略小括号,如下代码:
- print 'Test String';
- print('Test String');
3.printf
printf可以像C语言的printf一样,格式化输出一个字符串,它的格式和C语言差不多,都是以%开头,其说明符定义如下。
b 参数为整数,显示其二进制
c 参数为整数,显示对应ASCII字符
d 参数为整数,显示其十进制
f 参数为双精度,显示为浮点数
e 参数为双精度,显示为科学计数型
g 参数为双精度,显示为浮点数或科学计数型
o 参数为整数,显示其八进制
s 参数为字符串,显示为字符串
u 参数为无符号整数,显示其十进制
x/X 参数为整数,显示其十六进制(分别为大小写显示)
% 输出%
要说明的是:
f,e默认小数点后六位,g在超过六位(加小数点)时,会四舍五入,如果四舍五入之后的值小于1000000会直接输出,大于的1000000的话会显示成科学计数型,f在值大于1.2e23输出的结果是不对的。
以上除%以外,其它的都可以指定输出总位数(小数点、E都算一位),并可以指定0或空格为补位符,还可以指定补位在左还是在右。
f,e可以指定小数点后位数。
如 %5d 表示输出总位数为5,不足左补空格; %05d 表示输出总位数为5,不足左补0; %05.1f 表示输出总位数为5,不足左补0,小数点后1位; %-05.1f 表示输出总位数为5,不足右补0,小数点后1位;
示例代码如下:
- printf("%7.2f", 1.2); // " 1.20"
- printf("%-07.2f", 1.2); // "1.20000"
4.sprintf
sprintf和格式转换和printf一样,两者区别在于printf直接输出,而sprintf返回一个格式化后的字符串。
5.print_r和var_dump
print_r和var_dump都能输出数组和对象,但print_r对布尔型的输出不太明显;var_dump输出比较详细,一般调试时用得多,如下代码:
- $v = new test();
- print_r($v);
- var_dump($v);
- class test {
- public $num = 1;
- public $str = "222";
- public $bln = true;
- function test() {
- global $num;
- }
- }
- /*
- 结果为:
- test Object
- (
- [num] => 1
- [str] => 222
- [bool] => 1
- )
- object(test)#1 (3) {
- ["num"]=>
- int(1)
- ["str"]=>
- string(3) "222"
- ["bool"]=>
- bool(true)
- }
- */
字符串比较和查找
1.字符串比较
在PHP中,可以用==(双等号)或者 ===(三等号)来比较字符串,两者的区别是双等号不比较类型,三等号会比较类型,它不转换类型;用双等号进行比较时,如果等号左右两边有数字类型的值,刚会把另一个值转化为数字,然后进行比较,这样的话,如果是纯字符串或者NULL时,会转化为0进行比较,同样,大小于号也和等号一样,比较时可能出现不正确的结果。
所以,比较字符串可以用PHP的自带函数strcmp和strcasecmp,其中strcasecmp是strcmp的变种,它会先把字符串转化为小写再进行比较,如下代码:
- var_dump(0 == 'Test');
- var_dump(0 == '');
- var_dump(5 > 'T');
- var_dump(strcmp(5, 'T'));
- /*
- 结果为(第1~3结果是不对的,只有第4个是对的):
- bool(true)
- bool(true)
- bool(true)
- int(-1)
- */
2.字符串处理
(1).子串,代码如下:
$sub = substr(string, start[, length]);
(2).子串替换,代码如下:
$newstring = substr_replace(string, new, start[, length]);
用这个函数可以实现字符串的插入,删除操作,这个函数的start和length可以为负数,分别表示从后开始计算以及保留最后几位不替换。
(3).字符串反序,代码如下:
$newstring = strrev(string);
(4).重复字符串,代码如下:
$newstring = str_repeat(string, count);
返回一个重复count次string的新字符串。
(5).填充字符串,代码如下:
$newstring = str_pad(to_pad, length[, with[, type]]);
其中type有:STR_PAD_RIGHT(默认)、STR_PAD_LEFT和STR_PAD_BOTH三种;with默认为空格,函数表示把to_pad字符串用with填充为一个长度为length的字符串,如下代码:
- // 子串
- var_dump(substr('1234567890', 8)); // 90
- var_dump(substr('1234567890', 0, 2)); // 12
- // 反方向子串
- var_dump(substr('1234567890', -8)); // 34567890
- var_dump(substr('1234567890', -8, -2)); // 345678
- var_dump(substr('1234567890', -8, 2)); // 34
- // 插入
- var_dump(substr_replace('1234567890', 'a', 0, 0)); // a1234567890
- // 删除
- var_dump(substr_replace('1234567890', '', 8)); // 12345678
- // 反方向删除
- var_dump(substr_replace('1234567890', '', -2, -1)); // 123456780
- // 替换
- var_dump(substr_replace('1234567890', 'a', 0, 1)); // a234567890
- // 反方向替换
- var_dump(substr_replace('1234567890', 'a', -2, -1)); // 12345678a0
- // 字符串反转
- var_dump(strrev('1234567890')); // 0987654321
- // 重复字符串
- var_dump(str_repeat('12', 3)); // 121212
- // 填充字符串
- var_dump(str_pad('a', 10, '12')); // a121212121
- var_dump(str_pad('a', 10, '12', STR_PAD_LEFT)); // 121212121a
- var_dump(str_pad('a', 10, '12', STR_PAD_BOTH)); // 1212a12121
3.分解字符串
在PHP中,字符串的分解用explode,合并用implode(join是implode的别名),标记用strtok,还有另一个函数slipt也可以分解(正则分解),但5.3以后版本已经不推介了, 另外PHP中还有一个sscanf()函数,用于读取字符串。
strtok标记时,用strtok($str, $token)来初始化,用strtok($token)来继续取值,代码如下:
- $str = '1,2,3';
- $arr1 = explode(',', $str); // array('1', '2', '3')
- $arr2 = explode(',', $str, 2); // array('1', '2,3')
- $str1 = implode(',', $arr1); // '1,2,3'
- $str2 = strtok($str, ','); // 1
- $str3 = strtok(','); // 2
- $str4 = strtok(','); // 3
- // array(86, 10, 88888888, 'Beijin')
- $arr3 = sscanf('+86(10)88888888 Beijin', '+%d(%d)%d %s');
4.字符串查找
在PHP中,字符串的查找有三个系列,返回位置的、返回字符串的、掩码个数匹配,其中,返回位置的的函数一共有两个,strpos()和strrpos();返回字符串的也有两个strstr()和strchr();返回掩码匹配数的函数有strspn()和strcspn()。
strpos表示从左边开始计数,返回要查找的字符串第一次出现的位置;strrpos表示从右边计数,返回要查找的字符串第一次出现的位置。
strstr表示从左边计数,返回要查找字符串第一次到结尾的子串(包括查找字符串),当查找的是字符时,可以用ascii码数字来表示字符;stristr表示不区分大小查找;strchr是strstr的别名;strrchr返回字符最后出现到结尾的子串。
strspn表示从左边计数,第一次出现非掩码之前的子串的字符数;strcspn表示从左边计数,第一次出现掩码之前的子串的字符数。
示例代码如下:
- $pos = strpos('This a hello world program', ' '); // 4
- $pos = strpos('This a hello world program', 32); // 4
- $pos = strrpos('This a hello world program', ' '); // 18
- $pos = strrpos('This a hello world program', 32); // 18
- $str = strstr('This a hello world program', ' '); // " a hello world program"
- $str = strstr('This a hello world program', 32); // " a hello world program"
- $str = stristr('This a hello world program', ' A'); // "a hello world program"
- $str = stristr('This a hello world program', 65); // "a hello world program"
- $str = strrchr('This a hello world program', ' '); // " program"
- $str = strrchr('This a hello world program', 32); // " program"
- $str1 = "12345 12345 12345";
- $len = strspn($str1, '12345'); // 5
- $len = strcspn($str1, ' '); //5
常用的字符串操作
1.访问单个字符
在PHP中,可以把字符串当成一个字符的数组,可以直接用数组的访问方法来访问字符串。如$str[0]。
在这里要注意的是,如果字符是ASCII码以外时,访问会有问题,因为这种访问只能取得一个字节。
2.删除空白字符
在PHP中,可以用trim(), ltrim(), rtrim()三个函数来删除字符串开头或结尾的空白字符。
其中,trim()用于删除字符前后的空白字符;ltrim()用于删除字符左侧的空白字符;rtrim()用于删除字符右侧的空白字符。
在默认情况下,会删除以下字符:空格( |Ox20)、制表符TAB(n|Ox09)、换行(n|OxOA)、回车(r|0x0D)、空字符(|Ox00)。
也可以自己在参数里指定。
3.改变大小写
strtolower() 把整个字符串转化为小写。
strtoupper() 把整个字符串转化为大写。
ucfirst() 把字符串的第一个字符转化为大写,其它字符不变。
ucwords() 把字符串里的每一个单词的第一个字符转为大写,其它字符不变。
4.HTML转义
HTML转义是指把字符串转化成HTML显示用的字符串,对此,PHP中有两个函数实现此功能。
htmlentities() 把除空格外的所有可以转换的字符都转成HTML形式。
htmlspecialchars() 把必要的(与符号&、双引号、单引号、大于号、小于号)转化为HTML形式。
5.URL转义
URL转义是指把字符串转化成URL字符串,对此,PHP中有两个函数实现此功能。
urlencode()和urldecode()是把空格转成+号,其它的转成URL字符串,前者转换,后者反转换
rawurlencode()和rawurldecode()是把空格转成%20号,即普通URL字符串,其它的转成URL字符串,前者转换,后者反转换
6.SQL转义
跟PHP最相关的两个数据库(MySQL和PostgreSQL)都是以反斜杠为转义符的(Oracle是自己定义,其它数据库没有测试),对此PHP中用addslashes()函数来添加这些反斜杠,用stripcslashes()函数来删除这些反斜杠
波比源码 » php字符串与字符串操作教程详解
levaquin 500mg canada levaquin pills
tadalafil 20mg uk tadalafil order purchase voltaren online
cialis 10mg generique tadalafil generique en pharmacie viagra 200mg en ligne
buy catapres 0.1 mg for sale meclizine 25mg cheap buy tiotropium bromide 9mcg for sale
buy zoloft for sale Buy viagra canada buy viagra 50mg pills
generic imuran 100 mcg brand name viagra sildenafil mail order us
naltrexone 50mg pill albenza canada aripiprazole canada
avlosulfon for sale online buy allegra 180mg generic buy generic aceon 4mg
glycomet 1000mg usa cialis 5mg uk cialis 5mg price
buy colchicine 0.5mg generic online blackjack spins website win real money online casino for free
buy diflucan generic buy sildenafil 100mg online buy sildenafil online cheap
free poker online poker online game buy tadalafil 20mg sale
buy deltasone 10mg online cheap mebendazole 100mg oral mebendazole buy online
order lamisil 250mg pills lamisil 250mg for sale amoxicillin 250mg over the counter
buy pioglitazone generic viagra 25mg price viagra for men over 50
ivermectin tablet price dapsone 100 mg price avlosulfon 100mg oral
where can i play poker online free roulette online online blackjack for money
adalat online buy order fexofenadine generic order fexofenadine 180mg generic
cost amoxil 500mg buy stromectol for humans australia ivermectin medication
buy carvedilol 25mg order oxybutynin for sale amitriptyline pill
generic alendronate 70mg furadantin 100mg cost order motrin pills
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. Metropol Halı Karaca Halı Öztekin ve Selçuklu Halı Cami Halısı ve Cami Halıları Türkiye’nin En Büyük Cami Halısı Fabrikasıyız…
buy doxycycline pill order doxycycline 100mg online methylprednisolone order
buy minocycline 50mg pill hytrin 5mg pill hytrin 5mg drug
cialis savings card viagra 150mg price viagra fast shipping
metformin 1000mg pill buy glycomet 500mg generic tamoxifen 10mg pills
buy clomiphene 100mg sale clomiphene cost buy prednisolone 10mg pills
order isotretinoin 20mg generic order generic ampicillin ampicillin 500mg uk
ivermectin 0.2mg buy ed medications online buy prednisone 40mg pills
isotretinoin 10mg sale amoxil 500mg pill buy azithromycin 500mg
zofran 8mg canada brand zofran 4mg buy sulfamethoxazole pills
order albuterol 2mg inhaler order synthroid generic order amoxiclav online
prednisolone online order buy lasix 40mg pills buy lasix without prescription diuretic
modafinil 100mg oral provigil 200mg pill lopressor 100mg without prescription
buy monodox generic acyclovir 400mg ca acyclovir pills
cheap propranolol order inderal pills generic coreg 6.25mg
buy ditropan sale buy generic tacrolimus 1mg oxcarbazepine 600mg pills
buy zocor 10mg without prescription zocor for sale sildenafil 100mg england
cefdinir pills pantoprazole 20mg oral order pantoprazole 40mg sale
alfuzosin 10 mg tablet generic uroxatral 10 mg diltiazem for sale
viagra 50mg us buy tadalafil low price tadalafil 40mg uk
order zetia generic purchase tetracycline buy methotrexate 5mg without prescription
purchase phenergan pills cost provigil tadalafil 10mg us
buy generic zyrtec sertraline usa order sertraline 50mg generic
cenforce without prescription order cenforce 50mg pill metformin medication
lexapro generic lexapro 20mg cost revia canada
buy generic atorvastatin 20mg viagra tablets buy sildenafil 100mg
order letrozole 2.5mg without prescription order femara online cheap viagra 50mg uk
ivermectin 3mg dosage order stromectol 3mg sale accutane for sale
brand amoxicillin buy amoxicillin without a prescription buy prednisolone tablets
accutane 20mg ca buy azithromycin pills cheap zithromax 500mg
buy gabapentin 600mg for sale purchase furosemide generic buy doxycycline pills
ventolin over the counter albuterol without prescription cheap levoxyl sale
buy doxycycline purchase ventolin pill clavulanate uk
order atenolol 100mg for sale order atenolol 100mg without prescription letrozole without prescription
glucophage 1000mg pill lipitor 10mg sale buy generic norvasc
crestor order purchase crestor motilium where to buy
order toradol generic buy cheap propranolol buy generic inderal for sale
order ranitidine for sale order ranitidine 300mg order celebrex
buy cymbalta tablets order glucotrol without prescription order piracetam 800mg online cheap
buy betnovate for sale order betamethasone 20 gm sale buy itraconazole without a prescription
progesterone 100mg price tinidazole pills buy olanzapine 10mg pill
nateglinide 120mg uk buy atacand without a prescription oral atacand 8mg
cleocin 150mg cheap erythromycin over the counter red ed pill
nolvadex over the counter cefuroxime 500mg pill buy cefuroxime generic
cheap careprost desyrel over the counter desyrel drug
order levitra 20mg generic levitra purchase plaquenil online cheap
buy benicar 20mg without prescription buy divalproex 500mg pill generic depakote
buy temovate generic cost buspirone 10mg order amiodarone 100mg generic
buy acetazolamide paypal buy diamox without a prescription order azathioprine 50mg sale
buy naproxen pills for sale naproxen 500mg generic buy generic prevacid
buy generic proventil for sale buy protonix 40mg online phenazopyridine price
buy generic adalat cost perindopril fexofenadine 180mg usa
order metoprolol 100mg pill medrol 4 mg tablet buy medrol sale
purchase septra pills bactrim 960mg sale buy cleocin pills for sale
clopidogrel 75mg tablet buy methotrexate generic buy warfarin online cheap
buy rhinocort for sale order ceftin sale buy generic careprost over the counter
robaxin uk purchase trazodone for sale buy sildenafil 50mg pill
buy avodart pills order ranitidine generic meloxicam 15mg uk
buy celebrex 100mg generic flomax 0.2mg cheap zofran 4mg price
brand spironolactone cost valtrex 500mg valacyclovir 500mg over the counter
order tretinoin gel online cheap tretinoin cream for sale buy avana 100mg online cheap
buy tadalafil tablets viagra 50mg price viagra brand
terbinafine 250mg pills trimox pill buy amoxicillin cheap
sulfasalazine 500 mg pill verapamil 120mg oral buy calan 240mg
brand meclizine 25 mg order meclizine 25 mg generic buy minocycline pills
movfor without prescription molnunat canada buy cefdinir 300 mg without prescription
over the counter ed pills buy viagra 100mg sale viagra 100mg oral
lansoprazole medication order prevacid 15mg without prescription pantoprazole 20mg canada
cost phenazopyridine 200mg phenazopyridine 200 mg without prescription buy amantadine
buy avlosulfon 100mg perindopril generic perindopril pill
top ed pills buy tadalafil pills order tadalafil 10mg
purchase fexofenadine generic oral altace 5mg amaryl 4mg price
etoricoxib 120mg sale order arcoxia pills astelin online buy
order cordarone pills order carvedilol online cheap phenytoin 100 mg tablet
order albendazole 400mg for sale abilify 30mg ca buy generic medroxyprogesterone over the counter
oral praziquantel 600 mg order praziquantel 600mg pill buy cyproheptadine no prescription
furadantin 100mg us buy nitrofurantoin without a prescription buy pamelor sale
order glucotrol 5mg glipizide uk order betnovate 20gm for sale
where can i buy anafranil buy clomipramine 25mg online buy prometrium 200mg pill
tinidazole 300mg cost oral zyprexa 10mg buy bystolic generic
oxcarbazepine 300mg sale purchase ursodiol generic buy ursodiol 150mg online
ciplox uk purchase cefadroxil generic cefadroxil sale
frumil 5mg price adapen cost purchase zovirax creams
buy fluoxetine pill naltrexone order online generic femara 2.5 mg
cost valcivir 500mg buy valcivir 500mg floxin for sale online