您的位置:首页 > 编程语言 > PHP开发

PHP字符串

2016-04-27 18:17 344 查看

字符串

正则表达式

PHP支持POSIX和Perl两种正则表达式实现的特性和语法。

POSIX



perl

perl与JavaScript的正则表示风格一致,故采用perl版的正则表达式。

preg_grep()


<?php
$a=array("pasta","steak","fish","potatoes");
$food = preg_grep("/^p/",$a,1); //当传入第三个参数1时,输出不匹配的所有元素
print_r($food);  //输出数组对应于输入数组的索引顺序
?>


preg_match();


<?php
$text = "ticketre are $500.";
preg_match("/a(re)/",$text,$match);
print_r($match) ; //输出一个array("are","re")
?>


preg_match_all()


<?php
$text = "ticketre are $500.";
preg_match_all("/a(re)/",$text,$match);
print_r($match) ; //$match[0]内是所有与模式完全匹配的所有字符串的数组,$match[1]中含有所有与模式第一个小括号匹配的元素,以此类推
?>


preg_quote()


<?php
$text = "ticket are $500.";
echo preg_quote($text); //在对正则表达式而言有特殊含义的字符前插入一个反斜线
//输出为"ticket are \$500\."
?>


preg_replace()


<?php
$text = "this is a link to http://www.wilsonliu.cn/."; echo preg_replace("/http:\/\/(.*)\//","<a href=\"\${0}\">\${0}</a>",$text);
?>

//preg_replace还可以对数组进行替换
<?php
$draft = "In 2007 the company faced plummeting revenues and scandal.";
$keywords = array("/faced/","/plummeting/","/scandal/");
$replacements = array("celebrated","skyrocketing","expansion");
echo preg_replace($keywords,$replacements,$draft);
?>


preg_replace_callback(pattern,callback,str)


<?php

function acronym($matches){
$acronym = array(
"WWW" => "World Wide Web",
"IRS" => "Internal Revenue Service",
"PDF" => "Portable Document Format"
);
if(isset($acronym[$matches[1]])){
return $matches[1] . "(" . $acronym[$matches[1]] . ")";
}else {
return $matches[1];
}
}
$text = "The <acronym>IRS</acronym>offers tax forms in <acronym>PDF</acronym>format on the <acronym>WWW</acronym>.";
$newtext = preg_replace_callback("/<acronym>(.*)<\/acronym>/U","acronym",$text);
print_r($newtext);
//The IRS(Internal Revenue Service)offers tax forms in PDF(Portable Document Format)format on the WWW(World Wide Web).
?>


preg_split()


<?php
$text = "wilson++++liu++++++tianna+++row";
$arr = preg_split("/\+{1,}/",$text);
foreach($arr as $p){
echo $p . "\n";
}
?>


其他字符串函数

strlen


strcmp
(区分大小写)

strcasecmp
(不区分大小写)

strtolower()
(全部转化为小写)

strtoupper()
(全部转化为大写)

正则表达式的替代函数

strtok
根据预定义的字符对字符串进行词法分析

<?php
$info = "wilson|world,china,change";
$tokens = ":|,";
$tokenized = strtok($info,$tokens);
while($tokenized){
echo "log:$tokenized \n";
$tokenized = strtok($tokens); //每次调用该函数只是对字符串的下一部分做词法分析,必须连续的调用该函数
}
?>


explode
根据预定义的定界符分解字符串

<?php
$info = "wilson | world, china , change";
print_r(explode(" ",$info));
?>


implode
将数组转换为字符串

<?php
$info = "wilson world china change";
$test = explode(" ",$info);
print_r(implode("*",$test));
?>


strpos(str,substr,offset)
找到substr在str中第一次出现的位置

strrpos(str,substr,offset)
找到substr在str中第一次出现的位置

str_replace
用另一个字符串替代字符串的所有实例

substr(str,start,len)

count_chars
字符串中字符计数

str_word_count()
字符串中单词总数计数

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: