Jump to content

Get the first common line of a file using preg_match


siddscool19

Recommended Posts

I want to know how to get the first line of the file for example this is the file

I am a good boy 23.
I am a good boy 34.
I am a good boy 24.
I am a good boy 21.
I am a good boy 45.

Now how could i get only the first line in match taking the case there is only a slight change in the lines and that we want to figure out. The numbers in the above case. I just want to get the first line and stop the function to get further lines. In the above case  i don't know the number of first line which I want to know. Which i can easily get to know using (.*) . But the thing is that how to get only the first line and not others. What codes i have to use?

We can say like that I want to use this coding

$content= "I am a good boy 23.
I am a good boy 34.
I am a good boy 24.
I am a good boy 21.
I am a good boy 45."

 

preg_match("/I am a good boy (.*)/",$content,$number);
echo $number[1];

 

Now the output which i get should be 23 not any other number how to do that?

Incorrect. Use:

$subject = "I am a good boy 34.";
preg_match('/([0-9]+)/', $subject, $match);
echo $match[1];

 

This might run into error if you use something like

$content= "28 brown cows 23.
28 brown cows 34.
28 brown cows 24.
28 brown cows 21.
28 brown cows 45.";

What the hell?

$content= "28 brown cows 23.

28 brown cows 34.

28 brown cows 24.

28 brown cows 21.

28 brown cows 45.";

 

This is an example:

$subject = "I am a good boy 34.";
preg_match('/([0-9]+)/', $subject, $match);

 

It obviously needs to be modified so each line that is read in from the file is passed into the regex to extract the number. $subject is used as an example

 

If the file is in a Unix format:

 

<pre>
<?php
$data = <<<DATA
I am a good boy 23.
I am a good boy 34.
I am a good boy 24.
I am a good boy 21.
I am a good boy 45.	
DATA;
preg_match('/(\d+)\.$/m', $data, $matches);
print_r($matches);
?>
</pre>

What I mean is that I have variable which contains stored text from a textarea form.

Now i want to get number from the middle or only first particular line. How to tell preg_match to get me  a particular line only rather searching all the lines?

All the lines are similar except their numbers.

<pre>
<?php
$data = <<<DATA
I am a good boy 23.
I am a good boy 34.
I am a good boy 24.
I am a good boy 21.
I am a good boy 45.	
DATA;

### 0-indexed.
$which_one = 4;
print_r(array_splice(explode("\n", $data), $which_one, 1));
?>
</pre>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.