【问题标题】:PHP/PCRE/regular expressions: stripping search term appartPHP/PCRE/正则表达式:剥离搜索词 appart
【发布时间】:2012-06-01 07:04:08
【问题描述】:

我尝试将一个典型的 Google 搜索字符串剥离到它的一部分。 即刺痛可能是:“如何”引擎-燃料

所以我想分别了解“如何”以及引擎和燃料

我尝试了以下 preg_match_all,但我也分别获得了 “如何to”,这可能会变得非常难以处理。

preg_match_all(
     '=(["]{1}[^"]{1,}["]{1})'
    .'|([-]{1}[^ ]{1,}[ ]{1})'
    .'|([^-"]{1}[^ ]{1,}[ ]{1})=si', 
  $filter, 
  $matches,
  PREG_PATTERN_ORDER);

有人知道怎么做吗?

【问题讨论】:

标签: php regex full-text-search pcre


【解决方案1】:

试试:

$q = '"how to" engine -fuel';
preg_match_all('/"[^"]*"|\S+/', $q, $matches);
print_r($matches);

将打印:

大批 ( [0] => 数组 ( [0] =>“如何” [1] => 引擎 [2] => -燃料 ) )

意思:

"[^"]*"    # match a quoted string
|          # OR
\S+        # 1 or more non-space chars

【讨论】:

  • 谢谢!它更小,做我想要的。帮了大忙!
【解决方案2】:

试试这个

(?i)("[^"]+") +([a-z]+) +(\-[a-z]+)\b

代码

if (preg_match('/("[^"]+") +([a-z]+) +(-[a-z]+)\b/i', $subject, $regs)) {
    $howto = $regs[1];
    $engine = $regs[2];
    $fuel = $regs[3];
} else {
    $result = "";
}

说明

"
(?i)        # Match the remainder of the regex with the options: case insensitive (i)
(           # Match the regular expression below and capture its match into backreference number 1
   \"           # Match the character “\"” literally
   [^\"]        # Match any character that is NOT a “\"”
      +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \"           # Match the character “\"” literally
)
\           # Match the character “ ” literally
   +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(           # Match the regular expression below and capture its match into backreference number 2
   [a-z]       # Match a single character in the range between “a” and “z”
      +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\           # Match the character “ ” literally
   +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(           # Match the regular expression below and capture its match into backreference number 3
   \-          # Match the character “-” literally
   [a-z]       # Match a single character in the range between “a” and “z”
      +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\b          # Assert position at a word boundary
"

希望这会有所帮助。

【讨论】:

  • 答案也很好,但我更喜欢另一个,因为它非常简单。仍然:非常感谢,祝您有美好的一天!
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多