Viewed   65 times

A php variable contains the following string:


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


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?



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

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);


PHP manual entry:

Credit where credit is due: email regex taken from preg_match manpage, and URL regex taken from:

Saturday, November 5, 2022

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

here you go

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

strtok() Documentation

Tuesday, November 22, 2022

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:

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 :