php字符串实例
2.双引号字符串
<?php
print "I have gone to the store."; print "The sauce cost \$10.25."; $cost= '$10.25'; print "The sauce cost $cost."; print "The sauce cost \$\061\060.\x32\x35."; ?>
3.用strpos()来查找子字符串
<?php $e_mail='abc@sina.com'; if(strpos($e_mail,'@')===false) { print 'There was no @ in the e-mail address!'; } else { print 'There was @ in the e-mail address'; } ?>
相等符要用=== ,不等符要用!== ,因为如果要找的字符串在开始处,那么会返回0,0和false相等。
4.提取子字符串substr()
string substr ( string
$string
, int $start
[, int $length
] )<?php print substr('watch out for that tree',6,5); ?>
如果$start 的值大于字符串的长度,substr()返回false
如果$start加$length超过了字符串的结尾,substr()返回从位置$start开始至字符串结尾的所有字符
如果$start是负值,substr()会从这个字符串的结尾处开始反向推算,来确定要返回的子字符串的开始位置
当一个负的$start值超过了这个字符串的开始位置时(例如,如果对于长度为20的字符串设置的$-27),substr()将$start的值视为0
如果$length是负值,substr()会从这个字符串的结尾处反向推算,来确定要返回的子字符串的结尾位置(也就是从结尾处去掉length的绝对值个字符)
5.替换子字符串substr_replace()
mixed substr_replace ( mixed
$string
, string $replacement
, int $start
[, int $length
] )<?php print substr_replace('My pet is a blue dog', 'fish', 12); print substr_replace('My pet is a blue dog', 'green', 12,4); $credit_card='4111 1111 1111 1111'; print substr_replace($credit_card, 'xxxx ', 0, strlen(($credit_card)-4)); ?>
结果
My pet is a fish My pet is a green dog xxxx 1111 1111 1111
6按字反转字符串
<?php $s="Once upon a time there was a turtle."; //将字符串分解为独立的字 $words=explode(' ',$s); //反转这个字数组 $words=array_reverse($words); //重建反转后的字符串 $s= implode(' ', $words); print $s; ?>
可简化的写成
$reversed_s= implode(' ', array_reverse(explode(' ', $s)));
运行结果
turtle. a was there time a upon Once
----------------
Lynx
The quieter you become,the more you are able to hear.