sanitize_comma_delimited( string|array $str, string $pieces_type = 'int' )

Description #

Sanitize comma delimited strings.

Parameters #

  • $str
    string | array (Required) Comma delimited string.
  • $pieces_type
    string (Optional) Type of piece, string or number. Default value: 'int'

Source #

File: includes/functions.php

function sanitize_comma_delimited( $str, $pieces_type = 'int' ) {
	$str = ! is_array( $str ) ? explode( ',', $str ) : $str;

	if ( ! empty( $str ) ) {
		$str       = wp_unslash( $str );
		$glue      = 'int' !== $pieces_type ? '","' : ',';
		$sanitized = array();
		foreach ( $str as $s ) {
			if ( '0' == $s || ! empty( $s ) ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
				$sanitized[] = 'int' === $pieces_type ? intval( $s ) : str_replace( array( "'", '"', ',' ), '', sanitize_text_field( $s ) );
			}
		}

		$new_str = implode( $glue, esc_sql( $sanitized ) );

		if ( 'int' !== $pieces_type ) {
			return '"' . $new_str . '"';
		}

		return $new_str;
	}
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment