...

View Full Version : add line break after ever '*'



shajiuddin
01-03-2012, 01:32 PM
Hi,

I have a variable where from I get a string like this (* aaaa * bbbb * cccc)

I need to put line break after every star * then it should like this

* aaaa
* bbbb
* cccc


How can I do it? please help!

I used str_replace but I failed to achieve that I require

Regards

melloorr
01-03-2012, 01:35 PM
What code did you try?

djm0219
01-03-2012, 01:38 PM
$b = str_replace('*',"\r\n*",'* aaaa * bbbb * cccc');
echo $b;

themousemaster
01-03-2012, 04:25 PM
Hi,

I have a variable where from I get a string like this (* aaaa * bbbb * cccc)

I need to put line break after every star * then it should like this

* aaaa
* bbbb
* cccc


How can I do it? please help!

I used str_replace but I failed to achieve that I require

Regards

I'm going to assume you meant "before every star", as that's what your example looks like.



Try using all single quotes or all double quotes in your code's function. Not sure if that would make a difference, but helps to be consistent.


That said, your fuction does look correct if you are trying to add line breaks to, say, a file or a text document. If you are trying to get line breaks on a webpage, then you don't use \r\n, you use <br>... which would make the function look like this:




$b = str_replace('*',"<br>*",'* aaaa * bbbb * cccc');
echo $b;

kbluhm
01-03-2012, 04:36 PM
The code was not posted by the OP... also, double-quotes were necessary to interpolate the carriage return and new line.

Fou-Lu
01-03-2012, 07:19 PM
That said, your fuction does look correct if you are trying to add line breaks to, say, a file or a text document. If you are trying to get line breaks on a webpage, then you don't use \r\n, you use <br>... which would make the function look like this

No don't do this. Keep it as line feeds, you can use nl2br if necessary to replace the feeds with <br />. There is no guarantee that the OP isn't intending to display this in an HTML textarea, and using <br /> would force a replacement of the <br /> to a linebreak anyway, so going the other way around is better. This will also allow the opportunity to ltrim the leading linefeed off and append a trailing one if desired.

createdigital
01-03-2012, 10:01 PM
Try this:



<?php

$b = preg_replace('#\*#', '\\1'."\r\n", $b);

echo $b;

?>



I have not actually tested this... I'm typing this from my iPhone. This was just off the top of my head, so no guarantees.

Fou-Lu
01-03-2012, 10:08 PM
Try this:



<?php

$b = preg_replace('#\*#', '\\1'."\r\n", $b);

echo $b;

?>



I have not actually tested this... I'm typing this from my iPhone. This was just off the top of my head, so no guarantees.

str_replace is substantially faster than preg, and with such a simple pattern a preg is a bit of a waste.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum