Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Last active September 13, 2015 09:50
Show Gist options
  • Save sword-jin/2efe273a37824a921148 to your computer and use it in GitHub Desktop.
Save sword-jin/2efe273a37824a921148 to your computer and use it in GitHub Desktop.
php cookbook String.
//截取字符串
$substring = substr($string,$start,$length);
//使用给定字符串替换
$new_string = substr_replace($old_string,$new_substring,$start);
//反转字符串
string strrev (string $string)
//反转字符串(单词)
$new_string = implode(' ', array_reverse(explode(' ', $string)));
//子字符串替换
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
//大小写转换
ucwords()
ucfirst()
strtolower()
strtoupper()
// 去空格(字符穿)
trim()
ltrim()
rtrim()
//去掉数组元素空格
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = ['apple', 'banana ', ' watermelon'];
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
//csv文件读写
fputcsv()
fgetcsv()
//格式化输出
$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),
array('The Scarlatti Inheritance','Robert Ludlum', 1971),
array('The Parsifal Mosaic','William Styron', 1979) );
foreach ($books as $book) {
print pack('A26A15A4', $book[0], $book[1], $book[2]) . "\n";
}
//也可以使用 str_pad() 来代替
$title = str_pad(substr($book[0], 0, 26), 26, ' ');
$author = str_pad(substr($book[1], 0, 15), 15, ' ');
$year = str_pad(substr($book[2], 0, 4), 4, ' ');
//将字符串转化为数组
str_split()
//分割字符串为数组
array explode ( string $delimiter , string $string [, int $limit ] )
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
打断字符串为指定数量的字串
string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment