This tutorial will discuss about a unique way to check if string ends with newline in php.
To check if string ends with a new line Character we can use the regular expression.
PHP provides a function preg_match(), which accepts a regular expression pattern as the first argument and a string as the second argument. If the given string matches the given regex pattern, then it returns 1, otherwise it returns 0.
So to check if string ends with a new line character we can use this regex pattern,
'/[\r\n]$/'
It make sure that the last character of the string should be \n
or \r
.
We can pass this regex pattern, into the preg_match()
function, along with the string. If it returns 1, then it means string ends with the newline character.
We have created a separate function for this,
Frequently Asked:
function endsWithNewline($str) { return preg_match('/[\r\n]$/', $str) === 1; }
It accepts a string is an argument and returns true if the string ends with in new line character in PHP.
Let’s see the complete example,
<?php /** * Checks if a string ends with a newline character using * regular expressions (preg_match()). * * @param string $str The string to check. * @return bool True if the string ends with a newline character, false otherwise. */ function endsWithNewline($str) { return preg_match('/[\r\n]$/', $str) === 1; } $strValue = "Last Coder!\n"; // Check if string ends with a newline character if (endsWithNewline($strValue)) { echo "The string ends with a newline character."; } else { echo "The string does not end with a newline character."; } ?>
Output
The string ends with a newline character.
Summary
We learned how to check if a string ends with a newline character in PHP.