Skip to content

Instantly share code, notes, and snippets.

@weakish
Last active December 30, 2015 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save weakish/7789997 to your computer and use it in GitHub Desktop.
Save weakish/7789997 to your computer and use it in GitHub Desktop.
php 练习题
<?php
/* 亚马逊举办图书优惠活动,满100减10,满200减50,满300减80,满400减120,满500减200。
* tree买了1本书价格是 54.9, noodles买了3本书45.8 36.5 50.2,
* laker买了5本书21.3 45.6 39.5 62.5 20.5
* fen买了8本书 50.6 20.4 36.7 45.6 19.8 60.5 44.3 55.0
* 70买了10本书 47.8 30.6 15.6 56.8 30.0 29.8 60.8 70.9 69.9 116.7,,
* 请计算出各位需要付的金额。*/
$tree = ["tree", [54.9]];
$noodles = ["noodles", [45.8, 36.5, 50.2]];
$laker = ["laker", [21.3, 45.6, 39.5, 62.5, 20.5]];
$fen = ["fen", [50.6, 20.4, 36.7, 45.6, 19.8, 60.5, 44.3, 55.0]];
$seventy = ["seventy", [47.8, 30.6, 15.6, 56.8, 30.0, 29.8, 60.8, 70.9, 69.9, 116.7]];
function price($shopping_list) {
$total = array_sum($shopping_list);
if ($total > 500) {
$aftermath = $total - 200;
}
elseif ($total > 400) {
$aftermath = $total - 120;
}
elseif ($total > 300) {
$aftermath = $total -80;
}
elseif ($total > 200) {
$aftermath = $total -50;
}
elseif ($total > 100) {
$aftermath = $total -10;
}
else {
$aftermath = $total;
}
return $aftermath;
}
array_map(
function($sl) {
echo $sl[0], ' need to pay ', price($sl[1]), "\n";
},
[$tree, $noodles, $laker, $fen, $seventy]
);
<?php
# 获取<img alt="SegmentFault" src="http://s.segmentfault.com/img/logo.png?13.10.21.1">里图片名称
$URL = '<img alt="SegmentFault" src="http://s.segmentfault.com/img/logo.png?13.10.21.1">';
function get_image_name($url) {
preg_match('/(img\/)([a-z0-9]+\.[a-z]+)/', $url, $image_name);
return $image_name[2];
}
echo get_image_name($URL);
<?php
# 将we're the sfer!写入sf.txt
$to_write_file = "sf.txt";
$to_write_content = "we're the sfer!";
file_put_contents($to_write_file, $to_write_content);
# 将www.baidu.com内容追加sf.txt
file_put_contents($to_write_file, 'www.baidu.com', FILE_APPEND | LOCK_EX);
  1. 搭好php环境,写出第一个hello word。
<?php
echo "hello world";
?>
  1. 输出你邮箱的用户名和域名
<?php

list($user, $domain) = explode('@', 'weakish@gamil.com');
echo $user;
echo $domain;

?>
  1. 匹配出blog.segmentfault.com的主域名segmentfault.com
<?php

list($main_domain, $top_level_domain) = array_slice(explode('.', 'dev.blog.segmentfault.com'), -2);
echo $main_domain, '.', $top_level_domain;

?>
<?php
const FILE_NAME = 'city.txt';
$city_list = explode("\n", file_get_contents(FILE_NAME));
$result = implode("\n", preg_grep("/[0-9]/", $city_list, PREG_GREP_INVERT));
file_put_contents(FILE_NAME, $result);
@lvye
Copy link

lvye commented Dec 4, 2013

不错,会用list,explode也找得很准确。
域名匹配其实有一个php函数parse_url

@hyigo
Copy link

hyigo commented Aug 18, 2014

学习了

@lxiaoxiang
Copy link

["tree", [54.9]] 这个语法只能在 php>5.4 工作

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment