Valhalla's string utilities extend PHP's existing string functions and operators to make advanced string manipulations, comparisons, and construction effortless.
Here is a list of each of the available functions in Collection and how they can be used. Note that each of these functions is static and therefore can be called without instantiating any objects.
startsWith:
Parameters:
$haystack
$needle
$encoding
(Optional) The character encoding for the string. Defaults to 'UTF-8'.Return Value:
Returns
true
if
$haystack
begins with
$needle
, otherwise returns
false
. Throws an \InvalidArgumentException exception if
$needle
is an empty string.
endsWith:
Parameters:
$haystack
$needle
$encoding
(Optional) The character encoding for the string. Defaults to 'UTF-8'.Return Value:
Returns
true
if
$haystack
ends with
$needle
, otherwise returns
false
. Throws an \InvalidArgumentException exception if
$needle
is an empty string.
truncateWithEllipsis:
Parameters:
$text
$maxLength
$ellipsis
(Optional) The suffix to stick to the end of the truncated string. Defaults to '...'.
$encoding
(Optional) The character encoding for the string. Defaults to 'UTF-8'.Return Value: Returns a shortened string suffixed with an ellipsis.
Shortens the string and adds an ellipsis to the end and returns a string that is exactly
$maxLength
characters or less (in the case that the string was already shorter than
$maxLength
). Throws an exception if
$ellipsis
is longer than
$maxLength
.
vsprintfNamed:
Parameters:
$format
A format string with named parameters surrounded with curly braces.
$args
$failOnMissing
(Optional) Whether or not to throw an exception if a parameter is missing. Defaults to true.Return Value:
Returns a string in the format of
$format
with values from
$args
inserted. Throws an \OutOfBoundsException expection if
$failOnMissing
is true and a parameter is missing.
Accepts a format string, an array of arguments, and an optional boolean
$failOnMissing
(defaults to
true
). Builds a string with named parameters. If
$failOnMissing
is true, throws an exception if a parameter for the format string is missing from the list of arguments; if it is not true, an empty string is inserted for the missing parameter.
Example:
$foo = array('age' => 5, 'name' => 'john');
echo vsprintfNamed("{name} is {age}", $foo);