正则表达式:在行开头的表达式,否则为 [英] Regex : expression at beginning of line OR NOT

查看:237
本文介绍了正则表达式:在行开头的表达式,否则为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP中的一些正则表达式,但是有些我不理解. 这是我的文字:

I'm trying to work with some regex in PHP but there is something i don't understand. Here is my text:

# fhzmvbzmvbzmb#@!
# blabla
# test
sbsfzzbg

假设我想像降价一样强调它.为什么以下功能仅适用于我的第二行?我希望它也适用于第三行.

And let's say i want to emphasise it as in markdown. Why does the following function apply to my second line only ? I would expect it to apply to the third line as well.

preg_replace("/\n(.*)\n/", "<h1>$1</h1>", $input_lines);

我也想赶上第一行.有没有一种方法可以写我尝试捕获的表达式,该表达式可能位于字符串的开头,也可能不在字符串的开头?我已经考虑过下一个功能,但是它似乎不起作用:

Also, i want to catch the first line. Is there a way to write the expression i am trying to catch could either be at the beginning of the string or not ? I've thought about the next function but it doesn't seem to work:

preg_replace("/(^|\n)(.*)\n/", "<h1>$1</h1>", $input_lines);

非常感谢. 皮尔里克

推荐答案

通过使用m修饰符,您可以将^$应用于每一行:

By using the m modifier, you can have ^ and $ apply to every line:

http://www.phpliveregex.com/p/4eb

从文档中:

默认情况下,PCRE将主题字符串视为由单个行"字符组成(即使实际上包含多个换行符). 行首"元字符(^)仅在字符串的开头匹配,而行尾"元字符($)仅在字符串的末尾或终止换行符之前匹配(除非设置了D修饰符) ).这与Perl相同.设置此修饰符后,行首"和行尾"结构分别与主题字符串中的任何换行符紧接或紧随其后,以及恰好在开始和结束时匹配.这等效于Perl的/m修饰符.如果主题字符串中没有"\ n"字符,或者在模式中没有出现^或$,则设置此修饰符无效.

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

这篇关于正则表达式:在行开头的表达式,否则为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆