• php经典实例


    1.遍历字符串

    <?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。

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

    2.读取文件信息

    <?php
    $fp = fopen('hello.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);
        print_r($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方法。

  • 相关阅读:
    js dom
    js Number string
    jq ajax数据交互
    js date 和 math
    js中英文网页切换
    日常使用
    php求和
    empty()
    时间戳、日期相互转换
    数组转字符串之间相互转换
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/2574508.html
Copyright © 2020-2023  润新知