在正则表达式中使用单词边界而不是空格


Using word boundary instead of spaces in regex

我试图使用正则表达式来去掉句子中的第一个和最后一个单词,但它只在我使用空格进行匹配时有效,但在我尝试使用单词边界时不起作用。为什么?

使用空格:

$inputX = "she hates my guts";
preg_match("~ .+ ~i", $inputX, $match);
print_r($match);

结果:

Array ( [0] => hates my )

使用单词边界:

$inputX = "she hates my guts";
preg_match("~'b.+'b~i", $inputX, $match);
print_r($match);

结果:

Array ( [0] => she hates my guts )

以下是单词边界:

 s h e   h a t e s   m y   g u t s 
^     ^ ^         ^ ^   ^ ^       ^

所以你的模式匹配如下:

 s h e   h a t e s   m y   g u t s 
^'_______________________________/^
|               |                 |
'b              .+                'b

如果你想去掉第一个和最后一个单词,我只需要用一个空字符串替换它们,使用以下模式:

^'W*?'w+'s*|'s*'w+'W*$

两个'W*都是为了说明可能的标点符号(即she hates my guts.),但如果不需要,可以删除它们。

如果你想删除句子中的第一个和最后一个单词,你可以:

  1. 空间上的explode()
  2. 使用array_slice()删除第一个和最后一个元素
  3. implode()再次返回

代码

$inputX = "she hates my guts";
$result = implode(" ", array_slice(explode(" ", $inputX), 1, -1));
var_dump($result);

输出

string(8) "hates my"