PHP String Polyfill Functions Collection

Coming from the world of C#, there are string functions I couldn’t find an exact equivalent in PHP. So I compiled those here.

String Contains

PHP String Contains is a simple function I created. Quiet similar to strpos or strstr, but in my case, I have used this in most of my projects since its function name is more readable and understandable. I find it to be cleaner, also, as it is returning boolean instead of int.

<?php
if (!function_exists('str_contains')){
/**
 * Checks if a specified substring occurs within this string.
 * @param string $haystack : The string to test.
 * @param string $needle : The string to seek.
 * @param string $offset : (Optional) Starts searching from specified index.
 */
function str_contains($haystack, $needle, $offset = 0){
	return (bool) strpos($haystack, $needle, $offset);
}

/**
 * Checks if a specified substring occurs within this string. (case insensitive)
 * @param string $haystack : The string to test.
 * @param string $needle : The string to seek.
 * @param string $offset : (Optional) Starts searching from specified index.
 */
function str_icontains($haystack, $needle, $offset = 0){
	return (bool) stripos($haystack, $needle, $offset);
}
}

It works by checking if a given needle is found in the haystack using strpos function. You can also define offset so it starts searching from the specified index.

Equivalent functions are provided for both case-sensitive and case-insensitive.

<?php
str_contains ( 'The quick little brown fox jumps over the lazy dog.', 'The' );
// Result: true

str_contains ( 'The quick little brown fox jumps over the lazy dog.', 'THE' );
// Result: false

str_icontains ( 'The quick little brown fox jumps over the lazy dog.', 'THE' );
// Result: true

Path Combine

Roughly equivalent to Microsoft .NET’s Path.Combine method, this function combines two strings into a path. However, this only handles when to place path separators in between the two strings given, whether given string is a valid path or not.

It works by trimming off separator characters on the left side of $path1 and the right side of $path2, which is then concatenated as $path1, the directory separator character, and $path2. The function also works with URLs.

<?php
if (!function_exists('str_combinepath')){
/**
 * Combines two strings into a path.
 * @param string $path1 : The first path to combine.
 * @param string $path2 : The second path to combine.
 * @param string $separator : (Optional) The directory separator. Default: OS specified.
 */
function str_combinepath($path1, $path2, $separator = DIRECTORY_SEPARATOR){
	$path1 = rtrim($path1, $separator);
	$path2 = ltrim($path2, $separator);
	return $path1 . $separator . $path2;
}
}
<?php
str_combinepath ('/home', 'usr/');
// Result: '/home/usr/'

str_combinepath ('/home/', 'usr/');
// Result: '/home/usr/'

str_combinepath ('c:\temp', 'subdir\file.txt', '\\');
// Result: 'C:\temp\subdir\file.txt'

// Also works for URL's
str_combinepath ('https://www.earlpeter.com', 'wp-admin', '/');
// Result: https://www.earlpeter.com/wp-admin

Starts With and Ends With

As the name suggests, this allows you to check whether a string starts with or ends with a specific string. There is also a variation for non-case sensitive checks.

<?php
if (!function_exists('str_startswith')){
/**
 * Check if a string starts with specified string
 * @param string $haystack : the string to be checked
 * @param string $needle : the string to search
 */
function str_startswith($haystack, $needle) {
    return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}

/**
 * Check if a string starts with specified string (case insensitive)
 * @param string $haystack : the string to be checked
 * @param string $needle : the string to search
 */
function str_istartswith($haystack, $needle) {
    return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}
}
if (!function_exists('str_endswith')){
/**
 * Check if a string ends with specified string
 * @param string $haystack : the string to be checked
 * @param string $needle : the string to search
 */
function str_endswith($haystack, $needle) {
    return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}

/**
 * Check if a string ends with specified string (case insensitive)
 * @param string $haystack : the string to be checked
 * @param string $needle : the string to search
 */
function str_iendswith($haystack, $needle) {
    return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}
}

Is Regex

A lot of times where you want user to input his own search filter. To make sure you don’t run into unwanted errors, you can check whether a given string is a valid regex pattern or not.

<?php
if (!function_exists('str_isregex')){
/**
 * Check if a string given is a valid regex
 * @param string $str : the string to be checked
 */
function str_isregex($str){
	// https://stackoverflow.com/a/10778344/4469947
	return (bool) preg_match("/^\/.+\/[a-z]*$/i", $str);
}
}

Wildcard Search Match

A wildcard search allows you to match uncertain characters with the asterisk symbol. Besides wildcard, this function also makes sure the given pattern is regex safe (escapes input first).

For example, *world.doc|*.pdf matches the following:

  • hello world.doc
  • world.doc
  • hello world.pdf
  • but not:
  • world hello.doc
  • hello world.html

but not

  • hello world.html
  • world hello.doc
<?php
if (!function_exists('str_matchpattern')){
/**
 * Check if a string given matches a certain pattern
 * @param string $pattern : the reference pattern * -> any, | -> or
 * @param string $str : the string to be checked
 */
function str_wildcardsearch($pattern, $str) {
    $pattern = preg_replace_callback('/([^*|])/',
        function($m){ return preg_quote("{$m[0]}", "/"); }, $pattern);
    $pattern = str_replace('*', '.*', $pattern);
    return (bool) preg_match('/^' . $pattern . '$/', $str);
}
/**
 * Check if a string given matches a certain pattern (case insensitive)
 * @param string $pattern : the reference pattern * -> any, | -> or
 * @param string $str : the string to be checked
 */
function str_iwildcardsearch($pattern, $str) {
    $pattern = preg_replace_callback('/([^*|])/',
        function($m){ return preg_quote("{$m[0]}", "/"); }, $pattern);
    $pattern = str_replace('*', '.*', $pattern);
    return (bool) preg_match('/^' . $pattern . '$/i', $str);
}
}

You can see more of my PHP gists here.