Solved

How can i get the line of the best the last occurrence

Posted on 2016-09-03
4
27 Views
Last Modified: 2016-09-07
How can I get the string of line 6, I found all the "is", now I just want line 6

My code:

This is a house
This house is green
dfuguifg
dfughdfuigd
dfguhguidfg
The house is very nice
dfhgdfighdf
dfghfugh98457654
Is this house yours?
e57687jbngjkbfh

Open in new window


I want:
Line 1:is 
Line 2: is
Line 6: is
Line 9:is

Open in new window

0
Comment
Question by:Jasmine Ikhreishi
  • 2
  • 2
4 Comments
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 41783009
I assume your strings are in a text file. If this is the case look at the code below:

get_file_lines.txt
This is a house
This house is green
dfuguifg
dfughdfuigd
dfguhguidfg
The house is very nice
dfhgdfighdf
dfghfugh98457654
Is this house yours?
e57687jbngjkbfh

Open in new window


get_file_lines.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

//get file as array
$lines = file('get_file_lines.txt');

//iterate through the array
for ($i = 0; $i < count($lines); $i++) {
	echo "Line $i: is {$lines[$i]}<br>";
}
$needle = 'this';
echo "<br>Look for occurrences of the string '$needle'<br>";

for ($i = 0; $i < count($lines); $i++) {
	//use strstr for case-sensitive search
	if (stristr($lines[$i], $needle)){
		echo "Line $i: is {$lines[$i]}<br>";
	}
}

Open in new window


You can see it in action here: http://test.webintenerife.com/get_file_lines.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41783241
Why the different spacing around "is" in the results example?  

What makes line 6 special?  

If it's the position of line 6 relative to the other lines, or the content of line 6, we would need you to explain what characteristic makes line 6 special.
0
 
LVL 30

Assisted Solution

by:Marco Gasi
Marco Gasi earned 250 total points
ID: 41783401
Sorry, I misread your question. This the updated code:
<?php
//https://www.experts-exchange.com/questions/28967535/How-can-I-get-all-the-occurrences-for-a-certain-string-and-its-line-number-if-possible.html
error_reporting(E_ALL);
ini_set('display_errors', 'On');

//get file as array
$lines = file('get_file_lines.txt');

for ($i = 0; $i < count($lines); $i++) {
	echo "{$lines[$i]}<br>";
}

$needle = 'is';
echo "<br>Look for occurrences of the string '$needle'<br>";

for ($i = 0; $i < count($lines); $i++) {
	//use strstr for case-sensitive search
	if (stristr($lines[$i], $needle)){
		$ln = $i+1;
		echo "Line $ln: is <br>";
	}
}

Open in new window


But Ray pointed out 2 interesting questions: about the first I thought that was just typos (and maybe I was wrong); about the second, we need a criterion to identify line 6 among the others...
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41783599
To supplement Marco's very good example, there are only a couple of things I would add.

First and most importantly, in computer science most things are numbered from zero, not from one.  This is the numeric offset from the beginning of the data structure.  So the first character of a string is the zero character, the first line of a file is the zero line, the first element of an array is the zero element,  the last element of an array is the count()-1, etc.  When you number a data sample starting from 1 (as E-E does), the sixth line will be numerically indexed "five" in the computer code that accesses this data.  Don't let that confuse you as you work with these data structures.

Second, for better or worse, computer programming is an activity that requires exacting precision and meticulous attention to detail.  And at the same time, there are myriad ways to get from the same inputs to the same outputs.  So it's important to state your objective clearly and in ways that remove as much ambiguity as possible.  If you want line #6, by number, we would use counters to determine if line #6 exists.  If you want to get a line by content  (and the content just happens to be in line #6), we would use content-matching to determine if/where the information exists.  When the title speaks of "last occurrence" and you write that you want "the string of line 6" but show us a collection of four line numbers with "is" there is confusion and ambiguity in the question.

So for this little exercise, I am recasting your question to find the word "nice" which is present in line #6 (offset #5).  See if this makes sense, and please ask follow up questions if there is still anything we have not covered!
https://iconoun.com/demo/temp_jasmine_3.php
<?php // demo/temp_jasmine_3.php
/**
 * https://www.experts-exchange.com/questions/28967535/How-can-i-get-the-line-of-the-best-the-last-occurrence.html
 */
error_reporting(E_ALL);
echo '<pre>';


// A REGULAR EXPRESSION TO ISOLATE THE WORD "nice"
$rgx
= '#'           // REGEX DELIMITER
. '\b'          // WORD BOUNDARY
. 'nice'        // LITERAL STRING
. '\b'          // WORD BOUNDARY
. '#'           // REGEX DELIMITER
;

// SIMULATE A FILE THAT HAS BEEN READ INTO A STRING WITH file_get_contents()
$filedata = <<<EOD
This is a house
This house is green
dfuguifg
dfughdfuigd
dfguhguidfg
The house is very nice
dfhgdfighdf
dfghfugh98457654
Is this house yours?
e57687jbngjkbfh
EOD;

// MAKE AN ARRAY
$arr = explode(PHP_EOL, $filedata);

// ITERATE OVER EACH LINE OF THE FILE
$hit = FALSE;
foreach ($arr as $key => $str)
{
    if (preg_match($rgx, $str))
    {
        echo PHP_EOL . "Regex: <b>$rgx</b> detected at line number <b>$key</b>: " . htmlentities($str);
        $hit = TRUE;
    }
}
if (!$hit) echo PHP_EOL . "<b>$rgx</b> was not detected";

Open in new window

Outputs:
Regex: #\bnice\b# detected at line number 5: The house is very nice

Open in new window

0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now