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.
Thanks!
CodePudding user response:
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;
}
}
CodePudding user response:
Does this do what you want?
<?php
$words = "word1, word2, word3";
$text = "This is word1 text word2";
$wordsArray = explode(', ',$words);
$replacedText = str_ireplace($wordsArray,'',$text);
if ($replacedText !== $text) {
echo "some logic";
} else {
echo "no logic";
}