preg_match_all 个带有句号正则表达式的空格
preg_match_all spaces with fullstops regex
我正在为我正在使用的一些方法编写一些单元测试,并且发现了一个奇怪的错误并且想要一些 Regex 的建议。
做的时候:-
$needle = ' ';
$haystack = 'hello world. this is a unit test.';
$pattern = '/\b' . $needle . '\b/';
preg_match_all($pattern, $haystack, $matches, PREG_OFFSET_CAPTURE, $offset)
我预计找到的位置是
[5, 12, 17, 20, 22, 27]
就像我这样做一样,得到 none 个完全匹配的单词
while (($pos = strpos($haystack, $needle, $offset)) !== false) {
$offset = $pos + 1;
$positions[] = $pos;
}
但是 preg_match_all 没有找到第 2 次出现 (12) space 在
之间
. this
这与\b边界标志有关吗?我怎样才能解决这个问题以确保它接收到其他这个?
谢谢
您必须在 preg_match_all()
中更改您的 $pattern
,如下所示:-
<?php
$haystack = 'hello world. this is a unit test.';
while (($pos = strpos($haystack, ' ', $offset)) !== false) {
$offset = $pos + 1;
$positions[] = $pos;
}
echo "<pre/>";print_r($positions);
preg_match_all('/\s/', $haystack, $matches,PREG_OFFSET_CAPTURE);
echo "<pre/>";print_r($matches);
注意:- 您需要使用 \s
来检查 white-spaces
您可以应用 if-else
来根据 $needle
更改 $pattern
:-
if($needle == ''){
$pattern = '/\s/';
}else{
$pattern = '/\b' . $needle . '\b/';
}
我正在为我正在使用的一些方法编写一些单元测试,并且发现了一个奇怪的错误并且想要一些 Regex 的建议。
做的时候:-
$needle = ' ';
$haystack = 'hello world. this is a unit test.';
$pattern = '/\b' . $needle . '\b/';
preg_match_all($pattern, $haystack, $matches, PREG_OFFSET_CAPTURE, $offset)
我预计找到的位置是
[5, 12, 17, 20, 22, 27]
就像我这样做一样,得到 none 个完全匹配的单词
while (($pos = strpos($haystack, $needle, $offset)) !== false) {
$offset = $pos + 1;
$positions[] = $pos;
}
但是 preg_match_all 没有找到第 2 次出现 (12) space 在
之间. this
这与\b边界标志有关吗?我怎样才能解决这个问题以确保它接收到其他这个?
谢谢
您必须在 preg_match_all()
中更改您的 $pattern
,如下所示:-
<?php
$haystack = 'hello world. this is a unit test.';
while (($pos = strpos($haystack, ' ', $offset)) !== false) {
$offset = $pos + 1;
$positions[] = $pos;
}
echo "<pre/>";print_r($positions);
preg_match_all('/\s/', $haystack, $matches,PREG_OFFSET_CAPTURE);
echo "<pre/>";print_r($matches);
注意:- 您需要使用 \s
来检查 white-spaces
您可以应用 if-else
来根据 $needle
更改 $pattern
:-
if($needle == ''){
$pattern = '/\s/';
}else{
$pattern = '/\b' . $needle . '\b/';
}