Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 398
Mr B Avatar asked Sep 23 '11 10:09

Mr B


People also ask

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What is \r and \n in regex?

\n. Matches a newline character. \r. Matches a carriage return character.

What is whitespace in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


1 Answers

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

like image 166
KodeFor.Me Avatar answered Oct 03 '22 02:10

KodeFor.Me