PHP 字符串操作(一)

01. 删除字符串两端的空格

使用:ltrim():删除左边的空格

    rtrim();删除右边的空格

    trim():删除两边的空格

所谓的空白符:换行符、回车符、空格符、水平和垂直制表符、以及空值null。

删除两端的空白符不仅能节省存储控件,还能是<pre>标签里面的数据或文本内容显得更加精准。


此外
上面函数还能用途删除字符串中的指定字符:将需要删除的字符作为第二个参数传入函数
<?php
//删除字符串开始的空格和数字
print ltrim('10 Print $A', ' 0..9');

//删除字符串结尾的分号
print rtirm('SELECT * FROM A;',';');
?>

02. 生成都好分割的数据

数据格式化逗号分割的值(Comma-spearated values, CSV),以便导入到电子表格或者数据库中

使用函数: fputcsv()有数组生成一行CSV格式的数据。
示例:
<?php
$sale = array( 	array('Northeast','01','10001','aa'),
				array('Northwest','02','10002','bb'),
				array('Southeast','03','10003','cc'),
				array('Southwest','04','10004','dd')
			);

$fh = fopen('sales.csv','w') or die('Can\'t open the file!');
foreach ($sale as $row){
	if( fputcsv($fh,$row) === false ){
		die("Can't write CSV");
	}
}
fclose($fh) or die("Can\'t close sale.csv");

?>


详细参见PHP函数文档

03. 解析都好分割的数据

<?php
$fp = fopen('sample.csv','r') or die('can\'t open the 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>\n';
fclose($fp) or die("can\'t close file");
?>

04 .  生成字段宽度固定的数据记录

如果需要格式化数据记录,使其中的每个字段都包含特定数量的字符。

pack()函数,向其传递一个空格填充模式的字符串序列作为参数。

个人感觉有点想批量的字符截取:
$books = array( array('Elmer Gantry', 'Sinad Leisd', 1927),
				array('The Scarlatti Inher', 'Robert Ludlum', 1971),
				array('The parsifal Mosaic', 'William Styron', 1979)
				);
foreach($books as $book){
	print pack('A25A15A4', $book[0], $book[1], $book[2]). "<br>";
}

当我将上面的print内容换成pack(‘A2A1A4’,。。。。)------------》得到的是
ElS1927
ThR1971
ThW1979
很显然


如果想用空格以外的字符来填充记录,需要使用substr来确保每个字段的值不会太长,而且还要使用sub_pad来保证每个字段值不会过短。
开代码示例:
<?php
$books = array( array('Elmer Gantry', 'Sinad Leisd', 1927),
				array('The Scarlatti Inher', 'Robert Ludlum', 1971),
				array('The parsifal Mosaic', 'William Styron', 1979)
				);
foreach($books as $book){
	$title = str_pad(substr($book[0], 0, 25), 25, '.');
	$author = str_pad(substr($book[1], 0, 15), 15, '.');
	$year = str_pad(substr($book[2], 0, 4), 4, '.');
	print "$title$author$year<br>";
}
?>

结果:
Elmer Gantry.............Sinad Leisd....1927
The Scarlatti Inher......Robert Ludlum..1971
The parsifal Mosaic......William Styron.1979
 具体参照PHP函数手册了

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

substr和unpack来解析固定宽度的数据,这边参考PHP经典实例的介绍,自定义功能性函数。
<?php
//substr获取指定长度规则下的字串	substr($str,$start,$end);

//unpack从二进制字符串里面对数据进行解包	unpack($format,$data);

//将字段名称和宽度分别以独立数组的形式作为参数传递给一个解析函数

function fixed_width_substr($field, $data){
	$r = array();
	for($i = 0; $i < count($data); $i++){
		$line_pos = 0;
		foreach($field as $field_name => $field_length){
			$r[$i][$field_name] = rtrim(substr($data[$i],$line_pos,$field_length));
			$line_pos += $field_length;
		}
	}
	return $r;
}

//利用unpack的解析函数
function fixed_width_unpack($format_string,$data){
	$r = array();
	for($i = 0; $i < count($data); $i++){
		$r[$i] = unpack($format_string,$data[$i]);
	}
	return $r;
}

//测试示例
$booklist  = <<<END
Elmer Gantry             Sinclair Lewis1927
The Scarlatti InheritanceRobert Ludlum 1971
The Parsifal Mosaic      Robert Ludlum 1982
Sophie's Choice          William Styron1979
END;

$books = explode("\n", $booklist);

$book_fields = array('title'=>25, 'author'=>14, 'publication_year'=>4);
$book_array = fixed_width_substr($book_fields,$books);

//或者

$book_array = fixed_width_unpack('A25title/A14author/A4publication_year',$books);

两个函数返回的结果都是

Array
(
    [0] => Array
        (
            [title] => Elmer Gantry
            [author] => Sinclair Lewis
            [publication_year] => 1927
        )

    [1] => Array
        (
            [title] => The Scarlatti Inheritance
            [author] => Robert Ludlum
            [publication_year] => 1971
        )

    [2] => Array
        (
            [title] => The Parsifal Mosaic
            [author] => Robert Ludlum
            [publication_year] => 1982
        )

    [3] => Array
        (
            [title] => Sophie's Choice
            [author] => William Styron
            [publication_year] => 1979
        )

)


另外还有个str_split($str,$num), split分离函数,返回数组,index从0开始。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值