Skip to content

Instantly share code, notes, and snippets.

@mchelen
Created November 5, 2020 16:27
Show Gist options
  • Save mchelen/0d02801e8a6ac0dde13ab9c0e6864caa to your computer and use it in GitHub Desktop.
Save mchelen/0d02801e8a6ac0dde13ab9c0e6864caa to your computer and use it in GitHub Desktop.
<?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
?>