Solved

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

Posted on 2016-09-03
4
37 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 31

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 110

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 31

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 110

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Get value in session when using dynamic information 24 41
Make login page safer 3 32
while read ID; do 4 58
PHP Curl Problem 10 41
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to count occurrences of each item in an array.
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 …

733 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