Jump to content

Recommended Posts

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!!

 

Link to comment
https://forums.phpfreaks.com/topic/238582-count-lines-in-string/
Share on other sites

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!

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
    }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.