使用 preg_match 在一些字符后分割字符串
我发现这段代码最多匹配 300 个字符,然后在下一个最近的断字处中断:
$var = 'This is a test text 1234567890 test check12.' # 44 chars
preg_match('/^.{0,300}(?:.*?)\b/iu', $var, $matches);
echo $matches[0];
44 低于 300,所以我希望输出与 $var 相同。
但输出是:
This is a test text 1234567890 test check12 # 43 chars
$matches[0] 没有在末尾给我点,但是 $var 却给了我。任何人都可以告诉我如何获得完整的字符串(带点)?
I found this code which will match at most 300 chars, then break at the next nearest word-break:
$var = 'This is a test text 1234567890 test check12.' # 44 chars
preg_match('/^.{0,300}(?:.*?)\b/iu', $var, $matches);
echo $matches[0];
44 is lower than 300, so I expect the output to be the same like $var.
But the output is:
This is a test text 1234567890 test check12 # 43 chars
$matches[0] is not giving me the dot at the end, however $var does. Anyone can tell me how to get the full string (with the dot)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可以通过以下方式获得预期结果:
\b
\b
替换为$
编辑:
在您的模式中字符串末尾的点充当单词边界,因此您可以匹配点之前的所有内容。如果您在
\b
之后放置.*
,您会发现它将与点匹配。有关正则表达式中单词边界如何工作的详细信息,请参阅此。
I could get the expected result by:
\b
\b
with$
EDIT:
In your pattern the dot at the end of the string is acting as a word boundary, so you are able to match everything before the dot. If you put a
.*
after the\b
, you'll see that it will match the dot.See this for more info on how word boundaries in regex work.
使用 preg_match 在 300 个字符处中断似乎是一个坏主意。为什么不直接使用:
这将为您提供在下一个空格处断开的前 300 个字符,而不使用正则表达式。
Using preg_match to break at 300 chars seems like a bad idea. Why don't you just use:
That will give you the first 300 chars broken at the next whitespace without using regular expressions.
我不确定你为什么想要这个。 这是我对类似问题的回答,但在前一个最近的空格处进行了剪切。
I'm not sure why you want this though. Here is my answer to a similar question, but cutting at the previous nearest space.
在你的
我认为你应该去掉 * 。这意味着它必须至少匹配一次,但最多匹配无限次。所以你会发现你的经期是在第二场比赛中。
说实话,我只会使用该模式
In your
You should get rid of the * I think. This means that it must match at least once, but up to infinite times. So you wil find that your period is in the second match.
TO be honest, I would just use the pattern