0

我想知道我可以使用哪种正则表达式来基本上提取给定字符串中前面有破折号的所有单词。我将使用它来允许用户从我的网站的搜索结果中省略某些单词。

例如,说我有

$str = "this is a search -test1 -test2";

我正在尝试将其保存"test1"并保存"test2"到数组中,因为它们前面有一个破折号。

谁能帮帮我

4

2 回答 2

3

使用以下模式/\-(\w+)/。例子:

$string = 'this is a search -test1 -test2';
$pattern = '/\-(\w+)/';
if(preg_match_all($pattern, $string, $matches)) {
    $result = $matches[1];
}
var_dump($result);

输出:

array(2) {
  [0] =>
  string(5) "test1"
  [1] =>
  string(5) "test2"
}

解释:

/.../ delimiter chars

\-    a dash (must be escaped as it has a special meaning in the regex language

(...) special capture group. stores the content between them in $matches[1]

\w+   At least one ore more word characters
于 2013-05-09T02:21:51.460 回答
2

这可以完成工作:

<pre><?php    
$string = 'Phileas Fog, Passe-Partout -time -day -@StrAn-_gE+*$Word²²²';
preg_match_all('~ -\K\S++~', $string, $results);
print_r($result);
于 2013-05-09T02:31:48.500 回答