I’m writing a trimming function that takes a string and finds the first newline \n character after the 500th character and returns a string up to the newline. Basically, if there are \n at indices of 200, 400, and 600, I want the function to return the first 600 characters of the string (not including the \n).
I tried:
$output = preg_replace('/([^%]{500}[^\n]+?)[^%]*/','$1',$output);
I used the percent sign because I couldn’t find a character class that just encompassed “everthing”. Dot didn’t do it because it excluded newlines. Unfortunately, my function fails miserably. Any help or guidance would be appreciated.
Personally I would avoid regex and use simple string functions:
You might need to check for
\r\nas well – i.e. normalize first usingstr_replace( "\r\n", "\n", $str ).