Skip to content

Instantly share code, notes, and snippets.

@dcavins
Last active May 30, 2023 21:02
Show Gist options
  • Save dcavins/37b2627d929247912d08 to your computer and use it in GitHub Desktop.
Save dcavins/37b2627d929247912d08 to your computer and use it in GitHub Desktop.
RegExp for finding articles and prepositions in a string
<?php
$needles = array( 'a', 'an', 'the', 'and', 'or', 'but', 'aboard', 'about', 'above', 'across', 'after', 'against', 'along', 'amid', 'among', 'anti', 'around', 'as', 'at', 'before', 'behind', 'below', 'beneath', 'beside', 'besides', 'between', 'beyond', 'but', 'by', 'concerning', 'considering', 'despite', 'down', 'during', 'except', 'excepting', 'excluding', 'following', 'for', 'from', 'in', 'inside', 'into', 'like', 'minus', 'near', 'of', 'off', 'on', 'onto', 'opposite', 'outside', 'over', 'past', 'per', 'plus', 'regarding', 'round', 'save', 'since', 'than', 'through', 'to', 'toward', 'towards', 'under', 'underneath', 'unlike', 'until', 'up', 'upon', 'versus', 'via', 'with', 'within', 'without', 'long' );
$needles = implode('|', $needles);
// ?: signifies a non-capturing group
// http://www.regular-expressions.info/captureall.html
$pattern = "/(?:(?:\b(?:$needles)\b(?:\W(?:$needles)\b)*))/";
$haystack = 'By the Light of the Silvery Moon and Stars except during or until Dawn';
$replacement = '(r)$0(/r)';
$new_haystack = preg_replace( $pattern, $replacement, $haystack );
echo PHP_EOL . 'before: ' . $haystack;
echo PHP_EOL . 'after: ' . $new_haystack;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment