Viewed   65 times

A php variable contains the following string:

<p>text</p>
<p>text2</p>
<ul>
<li>item1</li>
<li>item2</li>
</ul>

I want to remove all the new line characters in this string so the string will look like this:

<p>text</p><p>text2><ul><li>item1</li><li>item2</li></ul>

I've tried the following without success:

str_replace('n', '', $str);
str_replace('r', '', $str);
str_replace('rn', '', $str);

Anyone knows how to fix this?

 Answers

4

You need to place the n in double quotes.
Inside single quotes it is treated as 2 characters '' followed by 'n'

You need:

$str = str_replace("n", '', $str);

A better alternative is to use PHP_EOL as:

$str = str_replace(PHP_EOL, '', $str);
Thursday, August 11, 2022
 
1

You can use preg_replace to do it.

for emails:

$pattern = "/[^@s]*@[^@s]*.[^@s]*/";
$replacement = "[removed]";
preg_replace($pattern, $replacement, $string);

for urls:

$pattern = "/[a-zA-Z]*[://]*[A-Za-z0-9-_]+.+[A-Za-z0-9./%&=?-_]+/i";
$replacement = "[removed]";
preg_replace($pattern, $replacement, $string);

Resources

PHP manual entry: http://php.net/manual/en/function.preg-replace.php

Credit where credit is due: email regex taken from preg_match manpage, and URL regex taken from: http://www.weberdev.com/get_example-4227.html

Saturday, November 5, 2022
 
2

The backslash is still an escape character in single-quoted strings (it escapes literal single quotes).

This is illegal for instance (since the backslash escapes the closing quote):

$path = 'C:';

So \ must map to a literal backslash to avoid inadvertent escaping.

Friday, November 25, 2022
 
3

here you go

$str = strtok($input, "n");

strtok() Documentation

Tuesday, November 22, 2022
 
bsa0
 
1

To manipulate HTML it is generally a good idea to use a DOM aware tool instead of plain text manipulation tools (think for example what will happen if you enounter variants like <br/>, <br /> with more than one space, or even <br> or <BR/>, which altough illegal are sometimes used). See for example here: http://sourceforge.net/projects/simplehtmldom/

Friday, December 2, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :