blic Posted June 6, 2011 Share Posted June 6, 2011 Hi there, I have a string $str, and this string has a text with multiple lines. So let's say: $st= "hello everybody" So, if I echo that, I'll get: echo $st ===> hello everybody. If I use tag <pre>, I get: hello everybody So, how can I count the lines (in this case it would be 2)? In my problem I have a big string with several lines, and I want to extract a few lines, around a specific string. So I think if I can count the lines, I can do that.. Thanks!! Quote Link to comment https://forums.phpfreaks.com/topic/238582-count-lines-in-string/ Share on other sites More sharing options...
wildteen88 Posted June 6, 2011 Share Posted June 6, 2011 The \n escape character represents newlines. To get the number of lines you can do $count = substr_count($string, "\n"); Quote Link to comment https://forums.phpfreaks.com/topic/238582-count-lines-in-string/#findComment-1226043 Share on other sites More sharing options...
blic Posted June 6, 2011 Author Share Posted June 6, 2011 Hey, that helped, thanks! But I thought the solution would be different, so I'm still not sure how to find which line in my string contains a certain substring. I can find the position in terms of number of characters, but not in lines.. How can I find which line contains my string? thanks! Quote Link to comment https://forums.phpfreaks.com/topic/238582-count-lines-in-string/#findComment-1226050 Share on other sites More sharing options...
wildteen88 Posted June 6, 2011 Share Posted June 6, 2011 An alternative way would be take each line within your string and add it into an array. You'd then iterate over the lines within the array searching for the string. When the string is found return the current line. Example code // the string to search for $searchString = 'mystring'; // some example data to work with $data = 'Line 1 Line 2 mystring Line 3 Line 4'; // add each line into the array $lines $lines = explode("\n", $data); // iterate through the lines foreach($lines as $key => $line) { // check to see if the string is on the current line if(strpos($line, $searchString) !== FALSE) { // string has been found, tell the user on what line it is on echo "Found '$searchString' on Line " . ($key+1); break; // stop the loop } } Quote Link to comment https://forums.phpfreaks.com/topic/238582-count-lines-in-string/#findComment-1226058 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.