How to remove line breaks with PHP or JS - php

I've tried about everything to delete some extra \n characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.
And yes I've tried things like
In JS:
text.replace(/\n/g,"")
In PHP:
preg_replace("[\n]","",$result);
str_replace("\n","",$result);
and when I try
text.replace(/\n/g,"")
in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.
I'm desperate, picky and this is killing me. Any input is appreciated.
EDIT:
If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.
Answer Explanation:
Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!
In my case:
Why this works? str_replace('\n', '', $result)
And this doesn't? str_replace("\n", '', $result)
Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.
If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.

In php, use str_replace(array('\r','\n'), '', $string).
I guess the problem is you also have \r's in your code (carriage returns, also displayed as newlines).

In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.
text = text.replace(/\n/g,"")

Both of the PHP functions you tried return the altered string, they do not alter their arguments:
$result = preg_replace("[\n]","",$result);
$result = str_replace("\n","",$result);

Strangely, using
str_replace(array('\r','\n'), '', $string)
didn't work for me. I can't really work out why either.
In my situation I needed to take output from the a WordPress custom meta field, and then I was placing that formatted as HTML in a javascript array for later use as info windows in a Google Maps instance on my site.
If I did the following:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= str_replace(array('\r','\n'), '', $stockist_address);
This did not give me a string with the html on a single line. This therefore threw an error on Google Maps.
What I needed to do instead was:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= trim( preg_replace( '/\s+/', ' ', $stockist_address ) );
This worked like a charm for me.
I believe that usage of \s in regular expressions tabs, line breaks and carriage returns.

Related

PHP: remove MySQL formatting such as line break and commas

I'm making a CSV file, one of the database filed has stored a section called comments/note which obviously have some commas and line breaks in it too. Looked around the web found usage of preg_replace(), not much familiar with regular expressions there fore combined two different ones and not getting anything in result its totally blank and i know all records have some sort of comments in it
this i used
preg_replace( "/\r|\n/|/[,]/", "", $string )
Please what do I need to do here get one text back without line breaks and commas
Regards
You can do it using strip_tags() and preg_replace();
$clean_str = trim(preg_replace('/\s\s+/', '', strip_tags($string)));
or try this
$clean_str = str_replace(array("\r\n","\r","\n", ","), '', strip_tags($string));

PHP - newline and BR removal

I have a string
"PRINT CHIFFON<BR /><BR />
"
I am trying to remove any newline symbols and tags.
$i->colour_code = str_replace('<br>', '', strip_tags($i->colour_code));
$i->colour_code = str_replace('<br \/>', '', strip_tags($i->colour_code));
$i->colour_code = preg_replace("/[\n\r]/","",$i->colour_code);
That still does not work. Any ideas will be appreciated as this issue causes the whole system stop working
You don't need to escape the slash in the second line of replacements. In fact, since you're running it through strip_tags, you don't even need the first two replacements. Try this:
$i->colour_code = str_replace(Array("\n","\r"),"",strip_tags($i->colour_code));
Just make sure that $i->colour_code is not readonly.
What do you mean it does not work? I just made a test and your code does indeed work, you have a problem with $i->colour_code.
Since you seem okay to use preg_replace, I suggest using this line of code:
$i->color_code = preg_replace('/(<br>|<br ?\/>|\r|\n)/i', '', $i->color_code);
Unlike your examples, it will be case insensitive as well, so it doesn't matter if it is br or BR.

Removing Break Lines

I've asked this question before but I didn't seem to get the right answer. I've got a problem with new lines in text. Javascript and jQuery don't like things like this:
alert('text
text);
When I pull information from a database table that has a break line in it, JS and jQuery can't parse it correctly. I've been told to use n2lbr(), but that doesn't work when someone uses 'shift+enter' or 'enter' when typing text into a message (which is where I get this problem). I still end up with separate lines when using it. It seems to correctly apply the BR tag after the line break, but it still leaves the break there.
Can anyone provide some help here? I get the message data with jQuery and send it off to PHP file to storage, so I'd like to fix the problem there.
This wouldn't be a problem normally, but I want to pull all of a users messages when they first load up their inbox and then display it to them via jQuery when they select a certain message.
You could use a regexp to replace newlines with spaces:
alert('<?php preg_replace("/[\n\r\f]+/m","<br />", $text); ?>');
The m modifier will match across newlines, which in this case I think is important.
edit: sorry, didn't realise you actually wanted <br /> elements, not spaces. updated answer accordingly.
edit2: like #LainIwakura, I made a mistake in my regexp, partly due to the previous edit. my new regexp only replaces CR/NL/LF characters, not any whitespace character (\s). note there are a bunch of unicode linebreak characters that i haven't acknowledged... if you need to deal with these, you might want to read up on the regexp syntax for unicode
Edit: Okay after much tripping over myself I believe you want this:
$str = preg_replace('/\n+/', '<br />', $str);
And with that I'm going to bed...too late to be answering questions.
I usually use json_encode() to format string for use in JavaScript, as it does everything that's necessary for making JS-valid value.

Replace newline from MySQL TEXT field to parse w/ JSON

"replace newline" seems to be a question asked here and there like hundred times already. But however, i haven't found any working solution for myself yet.
I have a textarea that i use to save data into DB. Then using AJAX I want to get data from the DB in the backend that is in TEXT field and to pass it to frontend using JSON. But pasing JSON returns an error, as new lines from DB are not valid JSON syntax, I guess i should use \n instead...
But how do i replace newlinew from DB with \n?
I've tried this
$t = str_replace('<br />', '\n', nl2br($t));
and this
$t = preg_replace("/\r\n|\n\r|\r|\n/", "\n", $t);
and using CHAR(13) and CHAR(10), and still I get an error
the new line in textarea is equivalent to, i guess
$t = 'text with a
newline';
it gives the same error. And in notepad i clearly see that it is crlf
You need to escape all the characters that have a special meaning in JSON, not only line feeds. And you also need to convert to UTF-8.
There's no need to reinvent the wheel, json_encode() can do everything for you.
Prfff... >_< silly me
I've lost another slash before replacing with \n
$t = preg_replace("/\r\n|\n\r|\r|\n/", "\\n", $t);

Scrape a price off a website

I'm trying to scrape a price from a web page using PHP and Regexes. The price will be in the format £123.12 or $123.12 (i.e., pounds or dollars).
I'm loading up the contents using libcurl. The output of which is then going into preg_match_all. So it looks a bit like this:
$contents = curl_exec($curl);
preg_match_all('/(?:\$|£)[0-9]+(?:\.[0-9]{2})?/', $contents, $matches);
So far so simple. The problem is, PHP isn't matching anything at all - even when there are prices on the page. I've narrowed it down to there being a problem with the '£' character - PHP doesn't seem to like it.
I think this might be a charset issue. But whatever I do, I can't seem to get PHP to match it! Anyone have any ideas?
(Edit: I should note if I try using the Regex Test Tool using the same regex and page content, it works fine)
Have you try to use \ in front of £
preg_match_all('/(\$|\£)[0-9]+(\.[0-9]{2})/', $contents, $matches);
I have try this expression with .Net with \£ and it works. I just edited it and removed some ":".
(source: clip2net.com)
Read my comment about the possibility of Curl giving you bad encoding (comment of this post).
maybe pound has it's html entity replacement? i think you should try your regexp with some sort of couching program (i.e. match it against fixed text locally).
i'd change my regexp like this: '/(?:\$|£)\d+(?:\.\d{2})?/'
This should work for simple values.
'#(?:\$|\£|\€)(\d+(?:\.\d+)?)#'
This will not work with thousand separator like 234,343 and 34,454.45.

Categories