Find the Number of Lines in a String in PHP With Example

You can find the number of lines in a string in PHP by using the `substr_count()` function to count the occurrences of newline characters (`\n`) in the string. Here’s an example:

<?php

// Input string
$string = "This is line 1.\nThis is line 2.\nThis is line 3.";

// Counting the number of lines
$num_lines = substr_count($string, "\n") + 1; // Add 1 to count the last line without a newline character

// Output the result
echo "Number of lines in the string: $num_lines";

?>

Output:

Number of lines in the string: 3

In this example, the input string has three lines separated by newline characters (`\n`). The `substr_count()` function is used to count the occurrences of `\n`, and then 1 is added to account for the last line that might not end with a newline character.