preg_replace line break with space

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

preg_replace line break with space

Post by SmokyBarnable »

I have a string that has <br /> 's in it. I want to remove these and replace with just a space. However when I try to use preg_replace it changes them all to <> instead of just a space. Here is the code I'm using.

Code: Select all

$msg = preg_replace('<br />', ' ' , $msg);
Thanks for any help.
User avatar
theYinYeti
Forum Newbie
Posts: 15
Joined: Thu Oct 26, 2006 3:33 pm
Location: France

Post by theYinYeti »

Regular expressions must be surrounded by a delimiter. The most common delimiter is '/', but in your case you have a '/' inside the RE, so another character would be better; I often use '#':

Code: Select all

$msg = preg_replace('#<br />#', ' ' , $msg);
Apart from that, were I you, I'd rather write:

Code: Select all

$msg = preg_replace('#<br\s*/?>#', ' ' , $msg);
Yves.
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Re: preg_replace line break with space

Post by jmut »

SmokyBarnable wrote:I have a string that has <br /> 's in it. I want to remove these and replace with just a space. However when I try to use preg_replace it changes them all to <> instead of just a space. Here is the code I'm using.

Code: Select all

$msg = preg_replace('<br />', ' ' , $msg);
Thanks for any help.

Code: Select all

$string = preg_quote('<br />');
$msg = preg_replace("#$string#", ' ' , $msg);
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

I would think, you only need a string function for this...

Code: Select all

$msg = str_replace ( '<br />', ' ', $msg );
printf
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

printf wrote:I would think, you only need a string function for this...

Code: Select all

$msg = str_replace ( '<br />', ' ', $msg );
printf
so true :)
I just wanted to point out how preg_quote is useful in such cases.
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

Post by SmokyBarnable »

Thanks....all those replies were very helpful.

php is cool!

:P
Post Reply