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.
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).chr(128) => 'l', chr(197).chr(129) => 'L',
chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
// Euro Sign
chr(226).chr(130).chr(172) => 'E',
// GBP (Pound) Sign
chr(194).chr(163) => '');
$string = strtr($string, $chars);
} else {
// Assume ISO-8859-1 if not UTF-8
$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
.chr(252).chr(253).chr(255);
$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
$string = strtr($string, $chars['in'], $chars['out']);
$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$string = str_replace($double_chars['in'], $double_chars['out'], $string);
}
return $string;
}
The following function, seems_utf8(), will check if a string is UTF-8 encoded.
/**
* Checks to see if a string is utf8 encoded.
*
* @author bmorel at ssi dot fr
*
* @param string $Str The string to be checked
* @return bool True if $Str fits a UTF-8 model, false otherwise.
*/
function seems_utf8($Str) { # by bmorel at ssi dot fr
$length = strlen(
i = 0;
length; $i++) {
if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
elseif ((ord(
i]) & 0xE0) == 0xC0) $n = 1; # 110bbbbb
elseif ((ord(
i]) & 0xF0) == 0xE0) $n = 2; # 1110bbbb
elseif ((ord(
i]) & 0xF8) == 0xF0) $n = 3; # 11110bbb
elseif ((ord(
i]) & 0xFC) == 0xF8) $n = 4; # 111110bb
elseif ((ord(
i]) & 0xFE) == 0xFC) $n = 5; # 1111110b
else return false; # Does not match any model
for (
j <
j++) { # n bytes matching 10bbbbbb follow ?
if ((++
length) || ((ord(
i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
The utf8_uri_encode() function encodes the Unicode values to be used in the slug.
/**
* Encode the Unicode values to be used in the URI.
*
* @param string $utf8_string
* @param int $length Max length of the string
* @return string String with Unicode encoded for URI.
*/
function utf8_uri_encode($utf8_string, $length = 0) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
$string_length = strlen($utf8_string);
for (
i < $string_length; $i++) {
$value = ord($utf8_string[
value < 128) {
if ($length && ($unicode_length >= $length))
break;
$unicode .= chr($value);
$unicode_length++;
} else {
if (count($values) == 0) $num_octets = ($value < 224) ? 2 : 3;
$values[] = $value;
if ($length && ($unicode_length + ($num_octets * 3)) > $length)
break;
if (count( $values ) == $num_octets) {
if ($num_octets == 3) {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
$unicode_length += 9;
} else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
$unicode_length += 6;
}
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}
Finally, we can declare the slug() function, which will generate a slug from any UTF-8 string:
/**
* Sanitizes title, replacing whitespace with dashes.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a dash.
*
* @param string $title The title to be sanitized.
* @return string The sanitized title.
*/
function slug($title) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---
title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%
title);
$title = remove_accents($title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
After this, you can simply use the slug() function to sluggify anything.
<?php
// The following line of code would echo 'internationalization-is-awesome'
echo slug('Iñtërnâtiônàlizætiøn is awesome');
?>
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);
You're falling victim to the gotcha specified in the documentation - look under "notes" on the str_replace documentation
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
Essentially what's happening is the sequential replacements, as you passed an array as the second parameter:
- 1 is replaced with do 25 lat
- In that string, 2 is replaced with od 26 do 35 lat, giving you do od 26 do 35 lat5 lat
- In that string, 3 is replaced with pow. 35 r.z. giving you the final result you're seeing.
This is because str_replace array pairs are applied one after the other.
Try strtr:
$myVariable = 1;
$replacePairs = array(
1 => "do 25 lat",
2 => "od 26 do 35 lat",
3 => "pow. 35 r.z."
);
$myVariable2 = strtr($myVariable,$replacePairs);
echo $myVariable2;
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.
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
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{}}
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.
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);
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.