Reputation: 1186
If exists, I need to remove \r\n\r\n
at the very beginning and/or at the very end of string.
My issue is I couldn't achieve my aim with codes below.
//if exists, remove \r\n\r\n at the very beginning
$str = preg_replace('/^(\r\n\r\n)/', '', $str);
//if exists, remove \r\n\r\n at the very end
$str = preg_replace('/$(\r\n\r\n)/', '', $str);
maybe my html output's source view can give some clues to you. I don't know the reason but <br />
tags are not side-by-side. They position as one-under-the-other.
<br />
<br />
some text
...
...
some text<br />
<br />
Also below, I share my whole string manipulation code. My problematic 2 rows of code is a part of the code below. (The other parts except 2 rows of code above works well)
function convert_str ($str)
{
// remove excess whitespace
// looks for a one or more spaces and replaces them all with a single space.
$str = preg_replace('/ +/', ' ', $str);
// check for instances of more than two line breaks in a row
// and then change them to a total of two line breaks
$str = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\r\n\r\n", $str);
//if exists, remove \r\n\r\n at the very beginning
$str = preg_replace('/^(\r\n\r\n)/', '', $str);
//if exists, remove \r\n\r\n at the very end
$str = preg_replace('/$(\r\n\r\n)/', '', $str);
//if exists, remove 1 space character just before any \r\n
$str = str_replace(" \r\n", "\r\n", $str);
//if exists, remove 1 space character just after any \r\n
$str = str_replace("\r\n ", "\r\n", $str);
// if exists; remove 1 space character just before punctuations below:
// $punc = array('.',',',';',':','...','?','!','-','—','/','\\','“','”','‘','’','"','\'','(',')','[',']','’','{','}','*','&','#','^','<','>','|');
$punc = array(' .',' ,',' ;',' :',' ...',' ?',' !',' -',' —',' /',' \\',' “',' ”',' ‘',' ’',' "',' \'',' (',' )',' [',' ]',' ’',' {',' }',' *',' &',' #',' ^',' <',' >',' |');
$replace = array('.',',',';',':','...','?','!','-','—','/','\\','“','”','‘','’','"','\'','(',')','[',']','’','{','}','*','&','#','^','<','>','|');
$str = str_replace($punc,$replace,$str);
return $str;
}
Can you please correct me?
Thanks
BR
Upvotes: 1
Views: 5930
Reputation: 1233
You will want to use the trim() string function to handle this.
trim — Strip whitespace (or other characters) from the beginning and end of a string
Example:
$str = trim($str);
Upvotes: 2
Reputation: 1664
Try to replace
//if exists, remove \r\n\r\n at the very end
$str = preg_replace('/$(\r\n\r\n)/', '', $str);
by
//if exists, remove \r\n\r\n at the very end
$str = preg_replace('/(\r\n\r\n)$/', '', $str);
You can also try to use the Trim function (e.g. string trim ( string $str [, string $charlist = " \t\n\r\0\x0B" ] ) )
Upvotes: 0