Skip to content
Advertisement

If str_ireplace() doesn’t meet php condition

I have a code where I match comma-separated words to text using the str_ireplace() function:

$words = "word1, word2, word3";
$text = "This is word1 text word2";

if (str_ireplace(explode(', ', $words), '', $text) != $text) {
   /*any logic*/
}

Please tell me how can I do the reverse logic? Those. if nothing is found or matched.

else {} does not work.

Full code:

function get_matched_categories( $description_every ) {
    $correspondence_tables = get_field( 'correspondence_table', 'option' );
    $default_categories = get_field( 'default_categories', 'option' );
    if ( is_array( $correspondence_tables ) ) {
        $arr_cat = array();
        foreach ( $correspondence_tables as $child_correspondence ) {

            if ( str_ireplace( explode( ', ', $child_correspondence['keywords'] ), '', $description_every ) != $description_every ) {
                array_push( $arr_cat, get_cat_ID( $child_correspondence['category'] ) );
            } else {
                if ( is_array( $default_categories ) ) {
                    foreach ( $default_categories as $default_category ) {
                        array_push( $arr_cat, get_cat_ID( $default_category['default_category_name'] ) );
                    }
                } 
            }

        }
        return $arr_cat;
    }
}

Advertisement

Answer

The problem is that you’re adding the default categories whenever you don’t match the keywords in one element of $correspondence_tables, but it could match later elements.

The code to add the default categories should only be added if none of the keywords in $correspondence_tables are matched. You can tell if that happened at the end of the loop by checking if $arr_cat is empty.

function get_matched_categories( $description_every ) {
    $correspondence_tables = get_field( 'correspondence_table', 'option' );
    $default_categories = get_field( 'default_categories', 'option' );
    if ( is_array( $correspondence_tables ) ) {
        $arr_cat = array();
        foreach ( $correspondence_tables as $child_correspondence ) {

            if ( str_ireplace( explode( ', ', $child_correspondence['keywords'] ), '', $description_every ) != $description_every ) {
                array_push( $arr_cat, get_cat_ID( $child_correspondence['category'] ) );
            }
        }
        if (empty($arr_cat) && is_array($default_categories)) {
            foreach ( $default_categories as $default_category ) {
                array_push( $arr_cat, get_cat_ID( $default_category['default_category_name'] ) );
            }
        } 
        return $arr_cat;
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement