开发者

How to match whitespace, carriage return and line feed using regular expression in PHP?

开发者 https://www.devze.com 2023-04-07 15:14 出处:网络
I am working with a regular expression in PHP. I have the following string: 开发者_运维技巧<img

I am working with a regular expression in PHP. I have the following string:

开发者_运维技巧<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.

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).

Here is my regular expression:

strip_tags(preg_replace('/^\s*<img\s*.*\/?>\s*$/i', '[IMG]', $test));

Appreciate the help.


[\n\r]+ Will match new lines. For White spaces add [\n\r\s]+


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.

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


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 ***
0

精彩评论

暂无评论...
验证码 换一张
取 消