30秒的PHP代码片段(3)字符串-String & 函数-Function

本文来自GitHub开源项目

点我跳转

30秒的PHP代码片段

clipboard.png

精选的有用PHP片段集合,您可以在30秒或更短的时间内理解这些片段。

字符串

endsWith

判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回true,否则返回false

function endsWith($haystack, $needle)
{
    return strrpos($haystack, $needle) === (strlen($haystack) - strlen($needle));
}

Examples

endsWith('Hi, this is me', 'me'); // true

firstStringBetween

返回参数startend中字符串之间的第一个字符串。

function firstStringBetween($haystack, $start, $end)
{
    return trim(strstr(strstr($haystack, $start), $end, true), $start . $end);
}

Examples

firstStringBetween('This is a [custom] string', '[', ']'); // custom

isAnagram

检查一个字符串是否是另一个字符串的变位元(不区分大小写,忽略空格、标点符号和特殊字符)。

就是所谓的字谜
function isAnagram($string1, $string2)
{
    return count_chars($string1, 1) === count_chars($string2, 1);
}

Examples

isAnagram('fuck', 'fcuk'); // true
isAnagram('fuckme', 'fuckyou'); // false

isLowerCase

如果给定字符串是小写的,则返回true,否则返回false

function isLowerCase($string)
{
    return $string === strtolower($string);
}

Examples

isLowerCase('Morning shows the day!'); // false
isLowerCase('hello'); // true

isUpperCase

如果给定字符串为大写,则返回true,否则返回false

function isUpperCase($string)
{
    return $string === strtoupper($string);
}

Examples

isUpperCase('MORNING SHOWS THE DAY!'); // true
isUpperCase('qUick Fox'); // false

palindrome

如果给定字符串是回文,则返回true,否则返回false

回文,顾名思义,即从前往后读和从后往前读是相等的
function palindrome($string)
{
    return strrev($string) === (string) $string;
}

Examples

palindrome('racecar'); // true
palindrome(2221222); // true

startsWith

检查字符串是否是以指定子字符串开头,如果是则返回true,否则返回false

function startsWith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0;
}

Examples

startsWith('Hi, this is me', 'Hi'); // true

countVowels

返回给定字符串中的元音数。使用正则表达式来计算字符串中元音(A, E, I, O, U)的数量。

function countVowels($string)
{
    preg_match_all('/[aeiou]/i', $string, $matches);

    return count($matches[0]);
}

Examples

countVowels('sampleInput'); // 4

decapitalize

使字符串的第一个字母去大写。对字符串的第一个字母进行无头化,然后将其与字符串的其他部分相加。省略upperRest参数以保持字符串的其余部分完整,或将其设置为true以转换为大写。

function decapitalize($string, $upperRest = false)
{
    return lcfirst($upperRest ? strtoupper($string) : $string);
}

Examples

decapitalize('FooBar'); // 'fooBar'

isContains

检查给定字符串输入中是否存在单词或者子字符串。使用strpos查找字符串中第一个出现的子字符串的位置。返回truefalse

function isContains($string, $needle)
{
    return strpos($string, $needle);
}

Examples

isContains('This is an example string', 'example'); // true
isContains('This is an example string', 'hello'); // false

函数

compose

返回一个将多个函数组合成单个可调用函数的新函数。

function compose(...$functions)
{
    return array_reduce(
        $functions,
        function ($carry, $function) {
            return function ($x) use ($carry, $function) {
                return $function($carry($x));
            };
        },
        function ($x) {
            return $x;
        }
    );
}
...为可变数量的参数, http://php.net/manual/zh/func...

Examples

$compose = compose(
    // add 2
    function ($x) {
        return $x + 2;
    },
    // multiply 4
    function ($x) {
        return $x * 4;
    }
);
$compose(3); // 20

memoize

创建一个会缓存func结果的函数,可以看做是全局函数。

function memoize($func)
{
    return function () use ($func) {
        static $cache = [];

        $args = func_get_args();
        $key = serialize($args);
        $cached = true;

        if (!isset($cache[$key])) {
            $cache[$key] = $func(...$args);
            $cached = false;
        }

        return ['result' => $cache[$key], 'cached' => $cached];
    };
}

Examples

$memoizedAdd = memoize(
    function ($num) {
        return $num + 10;
    }
);

var_dump($memoizedAdd(5)); // ['result' => 15, 'cached' => false]
var_dump($memoizedAdd(6)); // ['result' => 16, 'cached' => false]
var_dump($memoizedAdd(5)); // ['result' => 15, 'cached' => true]

curry(柯里化)

把函数与传递给他的参数相结合,产生一个新的函数。

function curry($function)
{
    $accumulator = function ($arguments) use ($function, &$accumulator) {
        return function (...$args) use ($function, $arguments, $accumulator) {
            $arguments = array_merge($arguments, $args);
            $reflection = new ReflectionFunction($function);
            $totalArguments = $reflection->getNumberOfRequiredParameters();

            if ($totalArguments <= count($arguments)) {
                return $function(...$arguments);
            }

            return $accumulator($arguments);
        };
    };

    return $accumulator([]);
}

Examples

$curriedAdd = curry(
    function ($a, $b) {
        return $a + $b;
    }
);

$add10 = $curriedAdd(10);
var_dump($add10(15)); // 25

once

只能调用一个函数一次。

function once($function)
{
    return function (...$args) use ($function) {
        static $called = false;
        if ($called) {
            return;
        }
        $called = true;
        return $function(...$args);
    };
}

Examples

$add = function ($a, $b) {
    return $a + $b;
};

$once = once($add);

var_dump($once(10, 5)); // 15
var_dump($once(20, 10)); // null

variadicFunction(变长参数函数)

变长参数函数允许使用者捕获一个函数的可变数量的参数。函数接受任意数量的变量来执行代码。它使用for循环遍历参数。

function variadicFunction($operands)
{
    $sum = 0;
    foreach($operands as $singleOperand) {
        $sum += $singleOperand;
    }
    return $sum;
}

Examples

variadicFunction([1, 2]); // 3
variadicFunction([1, 2, 3, 4]); // 10

相关文章:
30秒的PHP代码片段(1)数组 - Array
30秒的PHP代码片段(2)数学 - Math

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值