You need to place the \n in double quotes. Inside single quotes it is treated as 2 characters '\' followed by 'n'
Try below code:
$s = "\n test@gmail.com \n";
$s = str_replace("\n", '', $s);
echo $s;
Answer from Manthan Dave on Stack OverflowYou need to place the \n in double quotes. Inside single quotes it is treated as 2 characters '\' followed by 'n'
Try below code:
$s = "\n test@gmail.com \n";
$s = str_replace("\n", '', $s);
echo $s;
You have to use double quotes. \n is not interpreted as newline with single quotes.
YOu could explode the string into an array :
$list = explode(',', $string);
var_dump($list);
Which will give you :
array
0 => string '22' (length=2)
1 => string '23' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
Then, do whatever you want on that array ; like remove the entry you don't want anymore :
foreach ($list as
value) {
if ($value == $usrID) {
unset($list[$key]);
}
}
var_dump($list);
Which gives you :
array
0 => string '22' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
And, finally, put the pieces back together :
$new_string = implode(',', $list);
var_dump($new_string);
And you get what you wanted :
string '22,24,25' (length=8)
Maybe not as "simple" as a regex ; but the day you'll need to do more with your elements (or the day your elements are more complicated than just plain numbers), that'll still work :-)
EDIT : and if you want to remove "empty" values, like when there are two comma, you just have to modifiy the condition, a bit like this :
foreach ($list as
value) {
if ($value == $usrID || trim($value)==='') {
unset($list[$key]);
}
}
ie, exclude the $values that are empty. The "trim" is used so $string = "22,23, ,24,25"; can also be dealt with, btw.
Another issue is if you have a user 5 and try to remove them, you'd turn 15 into 1, 25 into 2, etc. So you'd have to check for a comma on both sides.
If you want to have a delimited string like that, I'd put a comma on both ends of both the search and the list, though it'd be inefficient if it gets very long.
An example would be:
$receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1);
I would prefer to use method 1 as its cleaner and more organised also Method 1 gives opportunity to use pairs from other source eg: bad words table in database. Method 2 would require another loop of sort..
<?php
$time_start = microtime(true);
for(
i<=1000000;$i++){
// Method 1
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)\n<br />";
$time_start = microtime(true);
for(
i<=1000000;$i++){
// Method2
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)\n";
?>
Did Test 1 in (3.6321988105774 seconds)
Did Test 2 in (2.8234610557556 seconds)
Edit: On further test string repeated to 50k, less iterations and advice from ajreal, the difference is so miniscule.
<?php
$phrase = str_repeat("You should eat fruits, vegetables, and fiber every day.",50000);
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$time_start = microtime(true);
for(
i<=10;$i++){
// Method 1
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)\n<br />";
$time_start = microtime(true);
for(
i<=10;$i++){
// Method2
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)\n";
?>
Did Test 1 in (1.1450328826904 seconds)
Did Test 2 in (1.3119208812714 seconds)
Even if old, this benchmark is incorrect.
Thanks to anonymous user:
"This test is wrong, because when test 3 starts $phrase is using the results of test 2, in which there is nothing to replace.
When i add $phrase = "You should eat fruits, vegetables, and fiber every day."; before test 3, the results are: Did Test 1 in (4.3436799049377 seconds) Did Test 2 in (5.7581660747528 seconds) Did Test 3 in (7.5069718360901 seconds)"
<?php
$time_start = microtime(true);
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
for(
i<=1000000;$i++){
// Method 1
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)<br /><br />";
$time_start = microtime(true);
for(
i<=1000000;$i++){
// Method2
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)<br /><br />";
$time_start = microtime(true);
for(
i<=1000000;$i++){
foreach ($healthy as
v) {
if (strpos($phrase, $healthy[$k]) === FALSE)
unset($healthy[
yummy[$k]);
}
if ($healthy) $new_str = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 3 in ($time seconds)<br /><br />";
?>
Did Test 1 in (3.5785729885101 seconds)
Did Test 2 in (3.8501658439636 seconds)
Did Test 3 in (0.13844394683838 seconds)
You could use
function add_ampersand( $string ) {
$string = preg_replace( '/\band\b/', '&', $string );
return $string;
}
or
function add_ampersand( $string ) {
$string = str_replace( ' and ', ' & ', $string );
return $string;
}
The first one is better in the case "and" is next to the end of the string or next to a special character such as ', , or ..
Try this
function add_ampersand( $string ) {
$string = str_replace( ' and ', ' & ', $string );
return $string;
}
\n in single quotes is a literal \ and a literal n, rather than a \n, to get the line breaks you need to use double quotes:
$str = str_replace("</div>\r\n</li>\r\n</ul>", "</div>\r\n</li>\r\n</ul>\r\naaa", $str);
Also, you should be replacing \r\n not \n\r as Windows line breaks are a carriage return \r followed by a line break \n.
When you use single quotes the \r\n will be treated as string.
Use double quotes instead:
$str = str_replace("</div>\n\r</li>\n\r</ul>", "</div>\n\r</li>\n\r</ul>\n\raaa", $str);
EDIT
Can't you just do:
$str = str_replace('</ul>', "</ul>\n\raaa", $str);
If that isn't suited it's better to resort to rexeg.
Do you want this for generating slug?
Then you can do something like this:
$slugified = preg_replace('/[^-a-z0-9]+/i', '-', strtolower(trim($url)));
It will strip leading and trailing whitespace first, convert the string to lowercase, then replace all non-word characters (not a-z, 0-9 or -) with a single -
A Beautiful *# Day will become a-beautiful-day
Remove strtolower() if you don't mind uppercase letters in the slug.
To generate slugs from any string (including strings with crazy UTF-8 characters), I use the following (taken from the WordPress source code). I realise it requires a little more code than the other answers posted here, but this is by far the most robust and complete solution to generating slugs automatically.
First, we need a remove_accents() function to convert all accent characters to ASCII characters, e.g. turn á into a.
/**
* Converts all accent characters to ASCII characters.
*
* If there are no accent characters, then the string given is just returned.
*
* @param string $string Text that might have accent characters
* @return string Filtered string with replaced "nice" characters.
*/
function remove_accents($string) {
if (!preg_match('/[\x80-\xff]/', $string))
return $string;
if (seems_utf8($string)) {
$chars = array(
// Decompositions for Latin-1 Supplement
chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
chr(195).chr(191) => 'y',
// Decompositions for Latin Extended-A
chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
chr(197). A new line and an n are two completely different characters.
New line is almost always represented as \n in programming languages, however, it is actually just character code 10 (decimal). n, on the other hand, is character code 110 (decimal). Other than the escape sequence, there is no relation at all between them.
To replace \n and only \n use:
$str = str_replace("\n", " ", $string);
Edit 1: For an example, see the snippet posted by Conner in the comment.
Edit 2: As noted by JoeCortopassi, PHP will only parse \n inside of certain types of string literals. For example, '\n' will end up in a literal \n string. (Character \ followed by character n).
"\n" //new line (char code 10)
'\n' //literal \ followed by n (char code 92 followed by char code 110)
"\\n" //literal \ followed by n (same as '\n')
'\\n' //literal \ followed by n (same as '\n' :p)
Or:
"\n" === chr(10)
'\n' === "\\n" === '\\n' === chr(92) . chr(110)
Option #1
If you have a string that is being displayed like so:
see\nyou\nsoon\n
...then you will want to use this:
$str = str_replace('\n', ' ', $string);
...because PHP will is displaying the backslash character followed by the character for 'n'. You use single quotes, because php interprets that as a literal string with no escaped characters.
`
Option #2
If, on the other hand, you have a string that is being displayed like so:
see
you
soon
...then you will want to use this:
$str = str_replace("\n", '', $string);
...because php will look at this string as something that needs to be interpreted. This means that variables will be processed, and escaped characters like \n, \t and \\ will be interpreted into their literal character values.
From what you're talking about, it sounds like your strings are litered with what should be new line statements, but that were never interpreted, so option #1 is probably you're best bet
Theres a better way to do this
<?
$str = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $str, 1); // outputs '123def abcdef abcdef'
?>
$str = implode($replace, explode($search, $subject, $count + 1));
Quick PoC:
$str =
"To be, or not to be, that is the question:
Whether 'tis Nobler in the mind to suffer
The Slings and Arrows of outrageous Fortune,
Or to take Arms against a Sea of troubles,
And by opposing end them";
/* Replace the first 2 occurrences of 'to' with 'CAN IT' in $str. */
echo implode('CAN IT', explode('to', $str, 3));
Output (emphasis added):
To be, or not CAN IT be, that is the question:
Whether 'tis Nobler in the mind CAN IT suffer
The Slings and Arrows of outrageous Fortune,
Or to take Arms against a Sea of troubles,
And by opposing end them
Note that this method is case sensitive.
PHP iterates the whole string for each array item you put in the $search parameter.
It is in fact replacing '{blah}' into '{blah{}}' with your first array item '{', and then from that into '{{}blah{{}}}' because there is another '{' after the first replacement.
You better off doing this with regular expression, with a single RegExp pattern it will run only once in your input string.
$str = preg_replace('/(\{|\})/', '{\\1}', '{blah}');
That's because the replacement itself contains the string to search for. I would rewrite it with preg_replace_callback instead:
echo preg_replace_callback('/{|}/', function($match) {
return $match[0] == '{' ? '{{}' : '{}}';
}, '{bla}');
// {{}bla{}}
If I understand well, you try to replace the \n by a HTML <br> ? If it is, you can use the nl2br function of PHP:
http://php.net/manual/en/function.nl2br.php
Ever considered using:
echo nl2br($Val);
Which makes your code more graceful than looking at:
$replace=str_replace("\n","<br>",$val);
$replace=str_replace("\r","<br>",$val);
$replace=str_replace("\n\r","<br>",$val);
as nl2br does exactly what your str_replace lines are doing and makes it easier.
This converts all the line break formats to the HTML <br>
Like this:
str_replace(array(':', '\\', '/', '*'), ' ', $string);
Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:
str_replace([':', '\\', '/', '*'], ' ', $string);
str_replace() can take an array, so you could do:
$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);
Alternatively you could use preg_replace():
$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
If you only have those 4 possibilities, yes, then you can do that with str_replace.
$str = str_replace( array( ' <!> ', ' <!>', '<!> ', '<!>' ), "\n", $str );
Yeah, but what if there is two spaces ? Or a tab ? Do you add a spacial case for each ?
You can either add special cases for each of those, or use regular expressions:
$str = preg_replace( '/\s*<!>\s*/', "\n", $str );
Of course, you can achieve this with 4 calls to str_replace. Edit: I was wrong. You can use arrays in str_replace.
$str = str_replace(' <!> ', "\n", $str);
$str = str_replace(' <!>', "\n", $str);
$str = str_replace('<!> ', "\n", $str);
$str = str_replace('<!>', "\n", $str);
Also consider using strtr, that allows to do it in one step.
$str = strtr($str, array(
' <!> ' => "\n",
' <!>' => "\n",
'<!> ' => "\n",
'<!>' => "\n"
));
Or you can use a regular expression
$str = preg_replace('/ ?<!> ?/', "\n", $str);
I used what you are doing with my own custom string.
I created 2 arrays, one with to find and one with replacements, as follows:
$search = ["fruit", "veg"];
$replace = ["pizza", "chips"];
From here, I then created the string to search:
$string = "Eating fruit and veg is good for you!";
And then using str_replace as such:
print str_replace($search, $replace, $string);
I got this result:
Eating pizza and chips is good for you!
As you can see, using an array within the str_replace function works!
The first argument for str_replace, string or string array, always refers to the needle.
The second argument for str_replace, string or string array, always refers to the replacement.
It should work like this:
str_replace(
["rn", "[B]"],
["<br>", "<b>"],
self::$post
);
In case you are wondering, [...] is identical to array(...), although it is new and less used.
You can use arrays as arguments in str_replace:
$a = strtoupper(str_replace(array('.php', '_'), array('', ' '), $a));
You could use str_replace() with arrays:
echo strtoupper(str_replace(['.php', '_'], ['', ' '], $a));
Note that the above statement uses the short array syntax, which is only available on PHP 5.4+. If you're using an older PHP version, you'll have to use the array(...) syntax:
echo strtoupper(str_replace(array('.php', '_'), array('', ' '), $a));
If the filename extension isn't known beforehand, you could use preg_replace_callback() instead:
echo preg_replace_callback('/(\w+)\..*/i', function ($m) {
return strtoupper(str_replace('_', ' ', $m[1]));
}, $a);
On Windows, a newline is \r\n. Since most of your users are probably on Windows, this would explain why just removing \n is insufficient.
Now, are these actual newlines you're trying to remove, or literal "backslash-n"? If it's an actual newline, then you should do something like:
str_replace(["\n","\r"],"",$text);
If it's a literal, then double up those backslashes.
you must use \n ,not \\n
function cleanComments($text){
return stripslashes(str_replace("\n", ". ",htmlspecialchars($text)));
}
this is because "\n" means new line and "\\n" means "\n" string;
example :
echo "\n";
result : a new line
echo "\\n";
result : \n
As Artelius explains, the last parameter to str_replace() is set by the function. There's no parameter that allows you to limit the number of replacements.
Only preg_replace() features such a parameter:
echo preg_replace('/John/', 'dude', $string, $numberOfInstances);
That is as simple as it gets, and I suggest using it because its performance hit is way too tiny compared to the tedium of the following non-regex solution:
$len = strlen('John');
while ($numberOfInstances-- > 0 && ($pos = strpos($string, 'John')) !== false)
$string = substr_replace($string, 'dude', $pos, $len);
echo $string;
You can choose either solution though, both work as you intend.
You've misunderstood the wording of the manual.
If passed, this will be set to the number of replacements performed.
The parameter is passed by reference and its value is changed by the function to indicate how many times the string was found and replaced. Its initial value is discarded.
foreach ($arr as $key => $string) {
$arr[$key] = str_replace("o", "0", $string);
}
OR
$arr = array_map(function ($el) { return str_replace("o", "0", $el);}, $arr);
You can use array_map (to map all values of an array to new ones using some transformation function) together with str_replace (to replace o by 0):
$arr = ['dog', 'cat', 'lion'];
$rep = array_map(fn($el) => str_replace('o', '0', $el), $arr);
(Note that this uses PHP 7.4 arrow function syntax. You can use function ($el) {
return str_replace('o', '0', $el) } instead of fn($el) => str_replace('o', '0', $el) if you have to use an older PHP version.)