3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Wrapper for strpbrk() except that it accepts a $length parameter * which will restrict the result string to this many characters. * * @param string $haystack The string where char_list is looked for. * @param string $char_list Case sensitive set of characters to look for. * @param int $length [optional] If given and is positive, the string returned will contain at most length characters. * @return false|string * @throws RangeException */ function strpbrkLength( string $haystack, string $char_list, int $length = null ) /*: false|string*/ { if( null !== $length && 0 > $length ) throw new RangeException( '$length must be null, zero or a positive integer.' ); $strpbrk = strpbrk( $haystack, $char_list ); if( false !== $strpbrk && null !== $length && strlen( $strpbrk ) > $length ) return substr( $strpbrk, 0, $length ); return $strpbrk; } $tests = [ [ 'haystack' => '', 'char_list' => 'r+', 'length' => null, 'expect' => false ], [ 'haystack' => '', 'char_list' => 'r+', 'length' => 0 , 'expect' => false ], [ 'haystack' => '', 'char_list' => 'r+', 'length' => 1 , 'expect' => false ], [ 'haystack' => 'r', 'char_list' => 'r+', 'length' => null, 'expect' => 'r' ], [ 'haystack' => 'r', 'char_list' => 'r+', 'length' => 0 , 'expect' => '' ], [ 'haystack' => 'r', 'char_list' => 'r+', 'length' => 1 , 'expect' => 'r' ], [ 'haystack' => 'r+', 'char_list' => 'r+', 'length' => null, 'expect' => 'r+' ], [ 'haystack' => 'r+', 'char_list' => 'r+', 'length' => 0 , 'expect' => '' ], [ 'haystack' => 'r+', 'char_list' => 'r+', 'length' => 1 , 'expect' => 'r' ], [ 'haystack' => 'r+', 'char_list' => 'r+', 'length' => 2 , 'expect' => 'r+' ], [ 'haystack' => 'w', 'char_list' => 'r+', 'length' => null, 'expect' => false ], [ 'haystack' => 'w', 'char_list' => 'r+', 'length' => 0, 'expect' => false ], [ 'haystack' => 'w', 'char_list' => 'r+', 'length' => 1, 'expect' => false ], [ 'haystack' => 'w+', 'char_list' => 'r+', 'length' => null, 'expect' => '+' ], [ 'haystack' => 'w+', 'char_list' => 'r+', 'length' => 0 , 'expect' => '' ], [ 'haystack' => 'w+', 'char_list' => 'r+', 'length' => 1 , 'expect' => '+' ], ]; foreach( $tests as $test => $args ) assert( strpbrkLength( $args[ 'haystack' ], $args[ 'char_list' ], $args[ 'length' ] ) === $args[ 'expect' ], "Failed test #$test" );
Output for 7.1.25 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.24, 7.4.0 - 7.4.13, 8.0.0