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

[PHP] php中的字符串处理函数

2016-01-06 15:09 706 查看
1.strpos查找字符串首次出现的位置

mixed strpos(string $haystack, mixed $needle, [, int $offset=0])

返回needle在haystack中首次出现的数字位置。

参数:

haystack:在该字符串中进行查找

needle:如果needle不是一个字符串,那么它将被转换为整型并被视为字符的顺序值

offset:如果提供了此函数,搜索会从字符串该字符数的起始位置开始统计。

<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);

if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
}
else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>

输出为 The string 'a' was found in the string 'abc' and exists at position 0

2.substr返回字符串的字串

string substr(string $string, int $start [, int $length])

返回字符串string由start和length参数指定的子字符串。

参数:

string:输入字符串

start:表示从什么位置返回字符串,可以为负数

length:返回的字符串将从start处开始最多包括length个字符,可以为负数

<?php
$myname = 'WANGPeng';
$familyname = substr($myname,0,4);
print $familyname;
?>

输出为WANG

3.substr_replace 替换字符串的子串

mixed substr_replace (mixed $string, mixed $replacement, mixed $start [, mixed $length ] )

substr_replace()在字符串string的副本中将由start和可选的length参数限定的子字符串使用replacement进行替换。

参数:

string:输入字符串

replacement:替换字符串

start:如果start为正数,替换将从string的start位置开始。也可以为负数。

length:如果为整数,表示string中被替换的子字符串的长度。

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<br/>";
echo substr_replace($var, 'bob', 0)."<br/>";
echo substr_replace($var, 'bob', 0, 5);
?>

输出为:

Original: ABCDEFGH:/MNRPQR/

bob

bobFGH:/MNRPQR/

4.逐字节处理字符串

利用for循环遍历字符串的每一个字节。

<?php
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i=0, $j=strlen($string); $i < $j; $i++){
if(strstr('aeiouAEIOU',$string[$i])){
$vowels++;
}
}
echo $vowels;
?>
输出14

5.按字(array_reverse)或按字节(strrev函数)来反转字符串

string strrev(string $string)

返回string反转后的字符串

<?php
print strrev('This is not a palindrome.');
?>
输出.emordnilap a ton si sihT

array array_reverse(array $array [, bool $preserve_keys = false])

array_reverse()接受数组array作为输入并返回一个单元为相反顺序的新数组。

参数:

array:输入的数组

preserve_keys:如果设置为 TRUE 会保留数字的键。 非数字的键则不受这个设置的影响,总是会被保留。

<?php
$s = "Once upon a time there was a turtle.";
//将字符串分解为独立的字
$words = explode(' ',$s);
//反转这个字符组
$words = array_reverse($words);
//重组反转后的字符串
$s = implode(' ',$words);
print $s;
?>

turtle. a was there time a upon Once

6.str_replace

mixed str_replace(mixed $search, mixed $replace, mixed $subject [, int &$count ])

该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。

参数:

search:查找的目标值,也就是needle。一个数组可以指定多个目标。

replace:search的替换值。一个数组可以被用来指定多重替换。

subject:执行替换的数组或者字符串。也就是haystack。

如果是数组,替换操作将遍历整个subject,返回值也将是一个数组。

count:如果被指定,它的值将被设置为替换发生的次数。

<?php
//赋值:<body text='black'>
$bodytag = str_replace("black", "red", "Paper is balck");
echo $bodytag;
echo "<br>";

//赋值:Hll wrld f PHP
$vowels = array("a","e","i","o","u","A","E","I","O","U");
$onlyconsonants = str_replace($vowels,"","Hello world of PHP");
echo $onlyconsonants;
echo "<br>";

//赋值 You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);
echo $newphrase;
echo "<br>";

//赋值:2
$str = str_replace("ll","","good golly miss molly",$count);
echo $count;
?>
输出为:

Paper is red

Hll wrld f PHP

You should eat pizza, beer, and ice cream every day.

2

7.控制大小写

<?php
print ucfirst("how do you do today?");
echo "<br>";
print ucwords("the prince of wales");
echo "<br>";
print strtoupper("i'm not yelling!");
echo "<br>";
print strtolower("CHINA");
?>
How do you do today?

The Prince Of Wales

I'M NOT YELLING!

china
8.在字符串中插入函数和表达式

当你想包含的值不能直接出现在字符串中时,就是用字符串连接操作符(.)

<?php
$amounts['payment'] = 100;
echo 'You owe '.$amounts['payment'].' immediately';
?>
You owe 100 immediately

9.删除字符串两端的空白符

ltrim()用于删除字符串开始出的空白符。

rtrim()用于删除字符串结尾处的空白符。

trim()用于删除字符串开始和结尾处的空白符。

<?php
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
?>


10.fputcsv -- 将行格式化为CSV并写入文件指针

int fputcsv(resource $handle, array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]])

将一行(用 fields 数组传递)格式化为 CSV 格式并写入由 handle 指定的文件。

handle:文件指针必须是有效的,必须指向由fopen()或fsockopen()成功打开的文件。

fields:值的一个数组

<?php
$sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
array('Northwest','2005-01-01','2005-02-01',546.33),
array('Southeast','2005-01-01','2005-02-01',93.26),
array('All Regions','--','--',1597.34));
$fh = fopen('php://output','w') or die("Can't open sales.csv");
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false){
die("Can't write CSV line");
}
}
fclose($fh) or die("Can't close sales.csv");
?>
显示:

Northeast,2005-01-01,2005-02-01,12.54 Northwest,2005-01-01,2005-02-01,546.33 Southeast,2005-01-01,2005-02-01,93.26 "All Regions",--,--,1597.34

如果将第6行改为,

$fh = fopen('sales.csv','w') or die("Can't open sales.csv");
则会生成一个csv文件,文件看上去如下:



11. 解析逗号分隔的数据

如果CSV数据包含在一个文件中,先用fopen()打开这个文件,然后用fgetcsv()函数读取其中的数据。下面例子是把CSV数据输出到了一个HTML表格中。

<?php
$fp = fopen('sales.csv','r') or die("Can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp)){
print '<tr>';
for ($i=0,$j=count($csv_line);$i<$j;$i++){
print '<td>'.htmlentities($csv_line[$i]).'</td>';
}
print "</tr>\n";
}
print '</table>';
fclose($fp) or die("can't close file");
?>
在浏览器中打开此php文件,显示为



12.解析字段宽度固定的数据记录

<?php
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while($s = fgets($fp,1024)){
$fields[1] = substr($s,0,10);
$fields[2] = substr($s,10,5);
$fields[3] = substr($s,15,12);
//调用对这个数组进行处理的函数
process_fields($fields);
}
fclose($fp) or die ("can't close file");
?>

13.分离字符串

explode — 使用一个字符串分割另一个字符串

array explode (string $delimiter, string $string [,int $limit])

此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 delimiter 作为边界点分割出来。

参数:

delimiter:边界上的分隔字符

string:输入的字符串

limit:如果设置了limit参数并且是正数,则返回的数组包含最多limit个元素,而最后那个元素将包含string的剩余部分。

<?php
$words = explode(' ','My sentence is not very complicated');
for ($x=0; $x<count($words); $x++){
echo $words[$x];
echo "<br>";
}
?>

输出:

My

sentence

is

not

very

complicated

split — 用正则表达式将字符串分割到数组中

array split(string $pattern, string $string [, int $limit])

preg_split — 通过一个正则表达式分隔字符串

array preg_split(string $pattern, string $subject [, int $limit = -1 [, int $flags = 0 ]])

通过一个正则表达式分隔给定字符串

参数:

pattern:用于搜索的模式,字符串形式。

subject:输入字符串

limit:如果指定,将限制分隔得到的子串最多只有limit个,返回的最后一个 子串将包含所有剩余部分。

flags:flags 可以是任何下面标记的组合(以位或运算 | 组合):

PREG_SPLIT_NO_EMPTY

如果这个标记被设置, preg_split() 将进返回分隔后的非空部分。

PREG_SPLIT_DELIM_CAPTURE

如果这个标记设置了,用于分隔的模式中的括号表达式将被捕获并返回。

PREG_SPLIT_OFFSET_CAPTURE

如果这个标记被设置, 对于每一个出现的匹配返回时将会附加字符串偏移量. 注意:这将会改变返回数组中的每一个元素, 使其每个元素成为一个由第0 个元素为分隔后的子串,第1个元素为该子串在subject 中的偏移量组成的数组

<?php
$words = split(' +','This sentence has some extra whitespace in it.');
$words = preg_split('/\d\. /','my day: 1. get up 2. get dressed 3. eat toast');
?>

使用spliti()或者在preg_split()中使用//i标志,表示匹配的分隔符不区分大小写。

<?php
$words = spliti(' x ','31 inches x 22 inches X 9 inches');
$words = preg_split('/ x /i','31 inches x 22 inches X 9 inches');
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: