Check if String Contains Line Break in PHP

This tutorial will discuss how to check if string contains line break in PHP.

To check if a string contains a line break in PHP, we can use regular expressions.

The regex pattern we can use is “/r|n/”. By passing this regex pattern and the string to the preg_match() function, we can determine if the given string contains a line break. If preg_match() returns 1, it means that the string contains a line break.

We have created a separate function for this,

function hasLineBreak($strValue)
{
    return preg_match("/r|n/", $strValue) === 1;
}

It accepts a string as an argument and returns true if the string contains a line break. The function utilizes the preg_match() function with the provided regex pattern to perform the check.

Let’s see the complete example,

<?php
/**
 * Check if a string contains a line break.
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string contains a line break, false otherwise.
 */
function hasLineBreak($strValue)
{
    return preg_match("/r|n/", $strValue) === 1;
}

$strValue = "This stringncontains a line break.";

// Check if string contains line break
if (hasLineBreak($strValue)) {
    echo "The string contains a line break.";
} else {
    echo "The string does not contain a line break.";
}
?>

Output

The string contains a line break.

Summary

Today, we learned how to check if string contains line break in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top