如何制作一个 . PHP 正则表达式模式中的(任何字符)也匹配换行符吗?

发布于 2024-09-29 00:09:56 字数 276 浏览 0 评论 0原文

PHP 正则表达式中的 . 字符接受除换行符之外的所有字符。我可以用什么来接受所有字符,包括换行符?

例如:

$text = <<<TEXT
foo
bar
TEXT;
preg_match('/.+/', $text, $match);
echo $match[0];

这会返回 foo,但我需要将完整的字符串匹配返回为:

foo
bar

The . character in a PHP regex accepts all characters except a newline. What can I use to accept ALL characters, including newlines?

For example:

$text = <<<TEXT
foo
bar
TEXT;
preg_match('/.+/', $text, $match);
echo $match[0];

This returns foo, but I need the full string match to be returned as:

foo
bar

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

灰色世界里的红玫瑰 2024-10-06 00:09:56

这通常用于捕获所有字符:

[\s\S]

您可以以相同的方式使用“Type-X + Non-Type-X”的任何其他组合:

[\d\D]
[\w\W]

但按惯例可以识别 [\s\S]作为“真正的任何东西”的简写。

如果通过 "s" 修饰符将正则表达式切换为“dotall”(又名“单行”)模式,您还可以使用 .。有时这不是一个可行的解决方案(例如,黑匣子中的动态正则表达式,或者如果您不想修改整个正则表达式)。在这种情况下,无论正则表达式如何配置,其他替代方案都会执行相同的操作。

This is commonly used to capture all characters:

[\s\S]

You could use any other combination of "Type-X + Non-Type-X" in the same way:

[\d\D]
[\w\W]

but [\s\S] is recognized by convention as a shorthand for "really anything".

You can also use the . if you switch the regex into "dotall" (a.k.a. "single-line") mode via the "s" modifier. Sometimes that's not a viable solution (dynamic regex in a black box, for example, or if you don't want to modify the entire regex). In such cases the other alternatives do the same, no matter how the regex is configured.

×眷恋的温暖 2024-10-06 00:09:56

. 字符表示“每个字符”(edit:OP 已编辑)。您需要将选项添加到正则表达式中,例如:

preg_match("`(.+)`s", "\n");

It's the the . character that means "every character" (edit: OP edited). And you need to add the option s to your regexp, for example :

preg_match("`(.+)`s", "\n");
新雨望断虹 2024-10-06 00:09:56

[.\n]+

不起作用吗?

(.|\n)+ 怎么样?我测试了它,它似乎有效。

我很确定这正是您所要求的字面解释。

would

[.\n]+

not work?

How about (.|\n)+? I tested it and it seems to work.

I am quite sure this is the literal interpretation of exactly what you were asking for.

皓月长歌 2024-10-06 00:09:56

PHP 手册Dot 页面指出:

如果设置了 PCRE_DOTALL 选项,则点也匹配换行符。

The PHP Manual page for Dot states that:

If the PCRE_DOTALL option is set, then dots match newlines as well.

脱离于你 2024-10-06 00:09:56

这里缺少一件重要的事情。 [\s\S] 匹配一个字符,而换行符可以是一个字符序列。 (Windows 使用两个字符:\r\n。). 都不是(使用 DOT_ALL 修饰符) 或 [\s\S] 将匹配换行符序列。匹配任何字符或任何换行符的最佳方式是 (.|\R),“除了换行符或换行符之外的所有内容”。 \R 匹配 \n\r\r\n

An important thing is missing here. [\s\S] matches one character, whereas a newline can be a character sequence. (Windows uses two characters: \r\n.) Neither . (with DOT_ALL modifier) nor [\s\S] will match the newline sequence. Best way to match any character or any newline is (.|\R), "everything except a newline or a newline". \R matches \n, \r and \r\n.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文