Last active
May 30, 2023 21:02
-
-
Save dcavins/37b2627d929247912d08 to your computer and use it in GitHub Desktop.
RegExp for finding articles and prepositions in a string
This file contains hidden or 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 | |
$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