Adding spaces in search phrase between alphabetics and numbers

Changing search input for better fuzzy matching

Often times combination of alphabetic and word inputs may yield no result if the input phrase is typed in without spaces.

Issue example

A post content contains these words:

Hello world 1235!

The user types in the following search phrase:

hello12345

The search will yield therefore NO result - because the search phrase "hello12345" does not match the content string in any way (phrase or it's parts are not a substring of the content).

For us humans this would be an obvious match, but the code can only look for parts of the search input. Words are by default only separated by word separators - commas, spaces, tabs etc..

Solution

What is this, and where do I put this custom code?

// Adding whitespace between numeric and alphabetical words
add_filter(
	'asp_query_args',
	function ( $args ) {
		$previous_char = '';
		$new_string    = '';
		foreach ( mb_str_split($args['s']) as $char ) {
			if (
			( is_numeric($previous_char) && ctype_alpha($char) ) ||
			( is_numeric($char) && ctype_alpha($previous_char) )
			) {
				$new_string .= ' ' . $char;
			} else {
				$new_string .= $char;
			}
			$previous_char = $char;
		}
		$args['s'] = $new_string;

		return $args;
	}, 10, 1
);

The custom code above will look for alphanumerics and numbers (and vice versa) in sequence and add spaces between them. Therefore typing in:

hello12345

..becomes:

hello 12345

This will match the original post content, therefore resolves the issue.

Combined solution with extra character removal

In this knowledge base is a solution to replace some special word boundary characters, in case needed, here is a combination of the two codes.

What is this, and where do I put this custom code?

// Special character removal & adding whitespace between numeric and alphabetical
add_filter(
	'asp_query_args',
	function ( $args ) {
		$characters   = "',._-?!"; // Type characters one after another
		$replace_with = ' ';     // Replace them with this (space by default)

		$args['s'] = str_replace(str_split($characters), $replace_with, $args['s']);

		$previous_char = '';
		$new_string    = '';
		foreach ( mb_str_split($args['s']) as $char ) {
			if (
				( is_numeric($previous_char) && ctype_alpha($char) ) ||
				( is_numeric($char) && ctype_alpha($previous_char) )
			) {
				$new_string .= ' ' . $char;
			} else {
				$new_string .= $char;
			}
			$previous_char = $char;
		}
		$args['s'] = $new_string;

		return $args;
	}, 10, 1
);

Last updated

Copyright Ernest Marcinko