[UPHPU] ereg_replace on newline character

David Smith DavidSmith at byu.net
Thu Oct 21 16:14:35 MDT 2004

<quote who="Benjamin Schmuhl">
> I need to remove any \n at the beginning of the string (regex:
> ^[\n]{1,10}), any at the end (regex: [\n]{1,10}$ ) and more than two \n
> anywhere within... but ereg_replace("\n","",$string) replaces n with "",
> as the \ here means: I really mean whatever the next character is.  So
> how do you say ^\n?

I lost parser context near the end there, but I think this may get the job
done for you:

Note: I don't know ereg syntax, but I prefer preg since it is faster (per
the PHP docs), and can be used in Perl as well.


// Remove preceding new-lines
$string = preg_replace( "/^\n*/m", "", $string );
// Remove trailing new-lines
$string = preg_replace( "/\n*$/m", "", $string );

// Optionally, you can replace the foregoing by
// removing all preceding and trailing white space
// (which includes \n):

// Remove preceding white space (can replace the previous code)
$string = preg_replace( "/^\s*/m", "", $string );
// Remove trailing white space
$string = preg_replace( "/^\s*/m", "", $string );

// Remove more than two \n occurrences (3 or more in a row)
$string = preg_replace( "/\n\n\n+/m", "", $string );


More information about the UPHPU mailing list