正则表达式 匹配以空格字符开头的行


Regular Expression Match lines that start with a space character

3.2 Mark one answer
You must NOT sound your horn
 between 10 pm and 6 am in a built-up
area
 at any time in a built-up area
 between 11.30 pm and 7 am in a builtup
area
 between 11.30 pm and 6 am on any
road
Vehicles can be noisy. Every effort must be
made to prevent excessive noise, especially
in built-up areas at night. Don’t

正则表达式

/^ (['w-,@'.?:=+&%$£@"'’'s ]+)/gmi

运行上面的正则表达式不会产生任何结果。我想要台词

我想要选项作为

between 10 pm and 6 am in a built-up
area
at any time in a built-up area
between 11.30 pm and 7 am in a builtup
area
between 11.30 pm and 6 am on any
road

如果你真的只需要以单个空格字符开头的所有行,你可以使用这个简单的正则表达式:

/^ (.*)$/gm

解释:

- "/" = Start of regular expression
- "^" = Match beginning of line
- " " = Match one space character
- "(.*)" = Match any sequence of characters and remember match
- "$" = regex ends at end of line
- "/" = End of regular expression
- gm = match [g]lobally and treat string as [m]ultiple lines
如果没有修饰符"m",字符"^"将匹配字符串的

开头,而"$"将匹配字符串的结尾。

具有preg_match_all函数的解决方案。
(我要感谢Wiktor Stribiżew提醒我水平/垂直空格字符'h'v

$text = "3.2 Mark one answer
You must NOT sound your horn
 between 10 pm and 6 am in a built-up
area
 at any time in a built-up area
 between 11.30 pm and 7 am in a builtup
area
 between 11.30 pm and 6 am on any
road
Vehicles can be noisy. Every effort must be
made to prevent excessive noise, especially
in built-up areas at night. Don’t";
preg_match_all("/^'h{1}.+?['r'n]{1}('H*?'b(?=['r'n]{1}))?/im", $text, $matches);
echo "<pre>";
var_dump($matches[0]);
// the output:
array(4) {
  [0]=>
  string(43) " between 10 pm and 6 am in a built-up
area
"
  [1]=>
  string(32) " at any time in a built-up area
"
  [2]=>
  string(45) " between 11.30 pm and 7 am in a builtup
area
"
  [3]=>
  string(39) " between 11.30 pm and 6 am on any
road
"
}

http://php.net/manual/en/regexp.reference.escape.phphttp://php.net/manual/en/regexp.reference.assertions.php