如何在 PHP 中使用正则表达式匹配空格、回车和换行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7527895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to match whitespace, carriage return and line feed using regular expression in PHP?
提问by Mr B
I am working with a regular expression in PHP. I have the following string:
我正在使用 PHP 中的正则表达式。我有以下字符串:
<img
src="/files/admin/hotel_website.gif" alt="Go To The Hotel's Web
Site" align="absmiddle" border="0" class="hotel_icon" />
This string contains carriage return and line feed characters.
此字符串包含回车符和换行符。
I want my regular expression to replace html img tags with IMG but this does not work with the above text.
我希望我的正则表达式用 IMG 替换 html img 标签,但这不适用于上述文本。
I discovered it contained these characters by looping through each character in the string and printing out the hexadecimal representation which can be found here (http://pastebin.com/ViNdBsRV).
我通过循环遍历字符串中的每个字符并打印出可以在此处找到的十六进制表示(http://pastebin.com/ViNdBsRV),发现它包含这些字符。
Here is my regular expression:
这是我的正则表达式:
strip_tags(preg_replace('/^\s*<img\s*.*\/?>\s*$/i', '[IMG]', $test));
Appreciate the help.
感谢帮助。
采纳答案by 3on
This:
这个:
preg_replace("#<img.+?/>#is", '[IMG]', $test)
Personally when I'm making a regular expression I always try to go the shortest/simplest.
Here you want to replace an entire tag, which starts with '<img
' and ends with '/>
', '.+?
' is a non greedy (lazy) catch.
And for the modifiers 'i
' for the case and 's
' to .
the possibility to be a new lines.
就个人而言,当我制作正则表达式时,我总是尝试使用最短/最简单的方法。在这里,您要替换以 ' <img
'开头并以 ' ' 结尾的整个标签,/>
' .+?
' 是一个非贪婪(懒惰)捕获。并且对于修饰符 ' i
' 的情况和 ' s
'.
的可能性是一个新行。
More on greedyness vs lazyness : http://www.regular-expressions.info/repeat.html
More on modifiers: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
更多关于贪婪与懒惰:http: //www.regular-expressions.info/repeat.html
更多关于修饰符:http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
回答by Merianos Nikos
[\n\r]+
Will match new lines. For White spaces add [\n\r\s]+
[\n\r]+
将匹配新行。对于空格添加[\n\r\s]+
回答by G Jeny Ramirez
This worked for me it matches multiple spaces and multilines, also any other character or symbol.
这对我有用,它匹配多个空格和多行,以及任何其他字符或符号。
[\S+\n\r\s]+
Hope this helps anyone.
希望这可以帮助任何人。
It matches for example:
它匹配例如:
stpd : asdfasdf
this is also matching ***