天天看点

php经典实例

1.遍历字符串

<?php

string="Thisweekend,I′mgoingshoppingforapetchicken.";string="Thisweekend,I′mgoingshoppingforapetchicken.";vowels = 0;

for(i=0,i=0,j = strlen(string);string);i<j;j;i++){

    if(strstr('aeiouAEIOU',string[string[i])){

        vowels++;     } } echovowels++;     } } echovowels;

?>

输出结果:14。

遍历字符串,获得其中所有的元音字母个数,这里的strstr(para1,para2)方法可以判断参数para2是否在para1字符串中,如果在则返回true,此时$vowels变量加1。当遍历完字符串后就可以获得最终的元音字幕个数了。时间复杂度为O(n)。

2.读取文件信息

fp=fopen(′hello.txt′,′r′)ordie("can′topenfile");while(fp=fopen(′hello.txt′,′r′)ordie("can′topenfile");while(s = fgets(fp,1024))$fields[1]=substr($s,0,10);$fields[2]=substr($s,10,5);$fields[3]=substr($s,15,12);printr($fields);fclose(fp,1024))$fields[1]=substr($s,0,10);$fields[2]=substr($s,10,5);$fields[3]=substr($s,15,12);printr($fields);fclose(fp) or die("can't close file");

hello.txt内容为:

hello, my name is jack.

hello, my name is tom.

hello, my name is jim.

输出结果:Array ( [1] => hello, my [2] => name [3] => is jack. ) Array ( [1] => hello, my [2] => name [3] => is tom. ) Array ( [1] => hello, my [2] => name [3] => is jim. )

首先打开文件hello.txt,然后一行一行地获取文件中的信息。将信息切分成三段保存到数组变量fields中。输出信息。

处理完成后,关闭文件。这里分别用到了fopen方法,fgets方法和fclose方法。

本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/archive/2012/07/03/2574508.html,如需转载请自行联系原作者