正则表达式问题:如何在文本不含指定单词时匹配全部内容
解决PHP/Drupal环境下的正则匹配需求
Got it, let's figure out the right regex for your Drupal backend in PHP. Since PHP uses PCRE-style regex, we can craft a pattern that meets your exact needs: matching the entire multi-line text only if it doesn't contain the word "student" (case-insensitive).
The Regex Pattern
/^(?:(?!student).)*$/is
Breakdown of the Pattern
Let's break down what each part does:
^: Anchors the match to the start of the string(?:(?!student).)*: A non-capturing group that repeats for every character:(?!student): Negative lookahead that checks the current position doesn't have "student" (case-insensitive, thanks to theimodifier) coming up next.: Matches any single character (including newlines, thanks to thesmodifier)
$: Anchors the match to the end of the stringi: Makes the match case-insensitive (so "Student", "STUDENT", etc. are all detected)s: Enables DOTALL mode, which lets the.character match newlines—critical for multi-line text
How to Use It in PHP
Here's a quick example of how you'd implement this in your Drupal code:
$targetText = "I need to think of something to write here. I am an alumni of the college. The blue cat is blue the red cat is red."; $regexPattern = '/^(?:(?!student).)*$/is'; if (preg_match($regexPattern, $targetText, $matches)) { // Text doesn't contain "student" (case-insensitive) — full text matched $matchedContent = $matches[0]; // Do something with $matchedContent in your Drupal logic } else { // Text contains "student" in any case — no match }
This pattern will reliably check the entire multi-line text, and only match if "student" (in any case) is nowhere to be found. It works perfectly with PHP's preg_match function, which is what you'll use in Drupal's backend.
内容的提问来源于stack exchange,提问作者Mona NM
相关产品推荐
相关产品推荐

