PHP 8.0 brought the super useful str_contains() function for checking if strings contain a sub-string. This has always been possible in PHP, but it required a more convoluted approach. Unfortunately, we don’t always have access to PHP 8 (or newer), and so I created the following little snippet to allow the function to be used in older versions of PHP. Simply include it somewhere in your PHP code to make use of it. In WordPress, I’ve just been dumping it in the wp-config.php file and once the servers are updated to PHP 8 eventually, I’ll simply remove the snippet from there.

Hopefully some of you find it useful.

<?php

/**
 * Shim for str_contains() support before PHP 8.
 * 
 * @param string $haystack The haystack.
 * @param string $needle The needle to find.
 * @return bool true if needle found, otherwise false.
 */
if ( ! function_exists( 'str_contains' ) ) {
	function str_contains( string $haystack, string $needle ) {

		if ( strpos( $haystack, $needle ) !== false ) {
			return true;
		}

		return false;
	}
}