preg_replace() Question - php

Currently, I'm using the following code:
preg_replace('/\s+/m','<br>',$var);
to replace line ends with <br> elements. An example of what I want:
Text Text Text
Text Text Text
Text Text Text
Should end up being:
Text Text Text<br>Text Text Text<br><br>Text Text Text
This does what it needs to, but I'd like to recognize when there is a double space and add two breaklines, instead of a single one. How can I do this, while retaining the current effect for single break lines?
I'm not too familiar with how preg_replace() works and I actually had to get help here to get that function in the first place. I took a look in the PHP manual and the function seemed a little confusing. Would anyone know of a site where I could learn how it works correctly?

You can simply replace each end-of-line character with <br />:
$var = str_replace(array("\r\n", "\n"), '<br />', $var);
There is no need to use a regular expression, but if you really want, you can use preg_replace to achieve the same effect:
$var = preg_replace("/\r?\n/", '<br />', $var);

you can do this by adding the g-modifier to the preg_replace like so:
preg_replace('/\s+/mg','<br>',$var);
preg stands for Perl Regular Expression - you'll find a lot more examples with this search string, e.g. this site or this site (I'm actually unsure, what the m-modifier does?)
Alternatively, you could use the simple $var = str_replace(' ', '<br', $var). I'm unsure, which one is faster.
Edit: If you want to replace newlines with html-breaks, use the nl2br() function.

php has a built in function for this
echo nl2br( $var );
this does \n, \r\n, \r, and \n\r
http://www.php.net/manual/en/function.nl2br.php

Check out this one. Not sure you are asking for that, but at least it works for me
$input = <<<DOC
Test Test Test
Test Test Test
Test Test Test
DOC;
$output = preg_replace("/$/m","<br/>",$input);
echo $output;
Hovewer, nl2br does just the same.

Is this what you’re trying to do?
<?php
$text = <<<EndText
Text Text Text
Text Text Text
Text Text Text
EndText;
$text = str_replace("\r", "", $text);
$text = str_replace("\n", "<br>", $text);
echo $text;
?>

Related

How to use get_file_content after use str_replace

I have problem with using get_file_content after preg_match and str_replace.
When I read from base, text look like:
Some text with shortcodes: [formularz {"agree":"1,1,1","option":"firstname,lastname,phone,email,company","leadfrom":"Allegro"}] [formularz {"agree":"0,1,0","option":"firstname,lastname,phone","leadfrom":"Allegro"}]
Then I looking my regular '[]':
preg_match_all('/\[formularz (.*)\]/',$campaign['content'],$matches);
Then I replace some chars and words:
echo str_replace($matches[0],str_replace([':','","','"','{','}'],['=','&','','file_get_contents("http:// mydomain.com/form.php?id_added_to_lead='.$id_added_to_lead.'&','")'],$matches[1]),str_replace(array("\r\n", "\r", "\n"), "",stripslashes($campaign['content']))) ;
And finally I have:
Some text with shortcodes:
file_get_contents("http:// mydomain.com/form.php?id_added_to_lead=100&agree=1,1,1&option=firstname,lastname,phone,email,company&leadfrom=Allegro")
file_get_contents("http:// mydomain.com/form.php?id_added_to_lead=100&agree=0,1,0&option=firstname,lastname,phone&leadfrom=Allegro")
What should I do, If I want to execute file_get_content in content?

remove \n from paragraph

I have a jquery editable div that when you click on it you can edit the text. The problem is that when the data is called from the db and placed into the paragraph I keep getting a \n for every space. How can I replace the \n with an actual new line.
I tried nl2br(), but that's not very convenient for my users since they then have to play with the <br /> when they want to edit the paragraph.
Any thoughts?
What about:
str_replace("\\n", "", $str); // see if this gets rid of them
Then this should work to put actual newlines in there:
str_replace("\\n", "\n", $str); // should replace with actual newline
try:-
$strippedText = str_replace(chr(10), '', $textFromDB);
or
$strippedText = str_replace(chr(10), '<br/>', $textFromDB);
Does this work? (Working on the possiblity that the newlines are already escaped).
$strippedText = str_replace('\\n', ' ', $textFromDB);
Are you using a ready made solution or making your own? I use http://aloha-editor.org/ for stuff like this and it's mostly problem free.
Have you tried str_replace?
$myTextFromDB = str_replace('\n', PHP_EOL, $myTextFromDB);
Ok, I think this is different enough that I should do a separate answer for it.
Are you saying a literal "slash n" shows up on the page? Or are you saying that your newlines show up as spaces?
If it's the latter, then there's no way around that. HTML will show newlines only as a space - you have to convert to br tags to break the line if it's not in a textarea context. But you can always convert them back to newlines when you pop that textarea up for your user and this should work well for people.

Limit amount of br's nl2br shows in a row?

I'm having some problems with a "bb parser" I'm coding. Or, well, not with the parser itself, but the nl2br modifying it.
The string from the database is like the following:
text text text
[code]code code code[/code]
text text text
Now, nl2br puts one br / after the first "text text text", and then another one below that, so there's two line breaks before the [code] tag (which actually is correct, but not what I want).
Is there any way I can limit how many br's are entered in a row? I can't seem to find a solution that's simple enough.
Thanks in advance, guys.
In addition to previous solution, I add a different one, since Fredrik asked for it. This will replace double <br> after nl2br instead of before.
$string = nl2br( $string );
$string = preg_replace( '/(<br(?: \\/)?>\\r?\\n?\\r?)(?=\\1)/is', '', $string );
You could for example replace two linebreaks (or more) by one by using preg_replace :-)
You could use
$string = str_replace(array("\r\n\r\n", "\n\r\n\r", "\n\n", "\r\r"), array("\r\n","\n\r","\n","\r"), $string);
This prevents double <br> tags. Preg_replace as suggested before is better if there could be more than two new lines in a row.

Replacing text function in php

I want to clean up some parsed text such as
\n the said \r\n\r\n\r\n I look in your eyes my dear\r\n\r\nI see green rolling Forests\r\n\r\nI see the far away Sky\r\n\r\nThey turn into the rain\r\n\r\n\r\nI see high soaring eagles... more\n
So I want to get rid of the "\n", "\r\n", "\r\n\r\n", "\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n" and "\r". That's all the combinations that appear in my parsed text.
Is there a way to do this in php?
If you just want 1 newline instead of multiple I would suggest this:
$clean = preg_replace(array("/\r+/","/(\n){2,}/"),array("","\n"),$text);
Otherwise str_replace to strip out newlines or nl2br will do the job. You could also adapt the regex to replace 1 or more newlines with a BR tag:
$clean = preg_replace(array("/\r+/","/\n+/"),array("","<br />"),$text);
What about
$text = str_replace(array("\n", "\r"), '', $text);
That will remove all new line characters.
If you want them as new lines, I'd change the replace to <br /> for HTML (or better still, use PHP's nl2br()), or standardise them in normal text with \n, for example.

PHP "backspace" character during output possible?

I have a feeling the answer is "it's not possible," but thought I'd ask to satisfy my curiosity.
I have some code that's echoed where the \n is unavoidable:
echo "Hello \n";
echo "World!";
I'd like the line to simply read (in the code output):
Hello World!
... thus removing the \n.
So I was wondering if it's possible to execute a "backspace" character during PHP's output?
Something simple like str_replace( "\n", 'backspace-character', $str );
Yes, the backspace character is ASCII character code 8 (According to the ASCII table), so you can output it in php using chr(). eg:
echo 'ab' . chr(8);
will output "a"
If the output target is HTML then extra spaces don't matter - browsers don't render multiple, contiguous spaces (which is why we have )
If the output target is something else, then you can simply cleanup the output. As you can see from other replies, there are a myriad of ways to do this. It seems like you're working with echo statements so the output-buffering functions will be the route you want to take.
ob_start();
echo "Hello \n";
echo "World!";
$output = preg_replace( "/ +/", ' ', str_replace( "\n", ' ', ob_get_clean() ) );
echo $output;
If you wanted to be able to do it for anything you could use the output buffer:
ob_start();
echo "Hello\n World";
$out = ob_get_contents();
ob_end_clear();
echo str_replace('\n', '', $out);
You could even use httaccess to append scripts containing this to any script called.
However, couldn't you just deal with it before it is set to stdout? Like
function print2($str){
echo str_replace("\n", '', $str);
}
This is not a direct answer to his exact question, but to what the title seems to allude to: outputting a PHP "backspace" character, which is probably only useful when using the PHP CLI.
You can find the right ASCII code for this (and other characters) on the ASCII table, and then use either chr() or an escape sequence:
echo chr(8);
echo "\010";
What about just replacing the "\n" by a white space (or just nothing, if you already have one space in your incoming string) ?
Like this, for instance :
$str = "Hello\nWorld!";
var_dump($str);
$str = str_replace("\n", ' ', $str);
var_dump($str);
The first output gives :
string 'Hello
World!' (length=12)
And the second one :
string 'HelloWorld!' (length=11)
Is that not enough ?
(Or maybe I don't understand the question well)
Can't you do it like this:
$str = str_replace("\n", ' ', $str);
while (strpos($str, ' ') !== false) // while there's two spaces in a row
$str = str_replace(' ', ' ', $str);
Now $str will have every spaces or \n characters sequences replaced by only one space.
(because if you just remove \n you migth have some place where a space is missing, and if you just replace it by a space you'll have some places with multiple spaces in a row).
EDIT: i don't know if the loop is really necessary but i don't have anything to test here if str_replace will automatically do the trick (and i don't think using regexp for such a simple thing is really a good idea).
Instead of thinking about how to do a backspace character, I would suggest rethinking the problem. Why do you want to take back some of your output? Probably because you outputted it too early.
Instead of doing an echo on the intermediary values, append them to the buffer. Then edit the buffer. Then print it out. If you can't control whether the output is produced or not (for example, you're using external vendor's library that outputs stuff), use PHP output buffering.
I don't know how to do a backspace, but if you are just trying to do a new line I would use:
echo "<br>";
PHP code allows for html code as long as it is used in a print or echo statement and is inside double quotes.

Categories