Created
November 5, 2020 16:27
-
-
Save mchelen/0d02801e8a6ac0dde13ab9c0e6864caa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// assumes fieldName is a text field with 1 value | |
function FilterNodesByRegex($nids, $fieldName, $regex) { | |
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids); | |
return array_filter($nodes, function($node) use ($regex, $fieldName) { | |
return preg_match( | |
$regex, | |
$node->get($fieldName)->getString() | |
); | |
}); | |
} | |
// example usage | |
// finds nids of type page with a field_my_rank value over 5 | |
$nids = \Drupal::entityQuery('node') | |
->condition('type', 'page') | |
->condition('field_my_rank', 5, '>') | |
->sort('nid', ASC) | |
->execute(); | |
// filters node list by field_my_text_input | |
$filteredResults = FilterNodesByRegex( | |
$nids, | |
'field_my_text_input', | |
'/^have a \w+ day/i' | |
); | |
// matches nodes where field_my_text_input is: | |
// have a nice day | |
// Have a great day | |
// have a pizza day | |
// does not match on: | |
// have a good time, it's a nice day | |
// clap your hands if you have a good day | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
references: