Find multiple lines in PHP

I am writing a PHP page that parses a given URL. What I can do is find only the first occurrence, but when I repeat it, I get a different value, not this one.

this is what i have done so far.

<?php $URL = @"my URL goes here";//get from database $str = file_get_contents($URL); $toFind = "string to find"; $pos = strpos(htmlspecialchars($str),$toFind); echo substr($str,$pos,strlen($toFind)) . "<br />"; $offset = $offset + strlen($toFind); ?> 

I know that the cycle can be used, but I do not know the conditions, nor the body of the cycle.

And how can I show the result that I need?

+7
string php
source share
4 answers

This is because you use strpos in htmlspecialchars($str) , but you use substr on $str .

htmlspecialchars() converts special characters to HTML objects. Take a small example:

 // search 'foo' in '&foobar' $str = "&foobar"; $toFind = "foo"; // htmlspecialchars($str) gives you "&amp;foobar" // as & is replaced by &amp;. strpos returns 5 $pos = strpos(htmlspecialchars($str),$toFind); // now your try and extract 3 char starting at index 5!!! in the original // string even though its 'foo' starts at index 1. echo substr($str,$pos,strlen($toFind)); // prints ar 

To fix this, use the same hay in both functions.

To answer another question about finding all occurrences of one line in another, you can use the third argument, strpos , offset, which determines where to look. Example:

 $str = "&foobar&foobaz"; $toFind = "foo"; $start = 0; while($pos = strpos(($str),$toFind,$start) !== false) { echo 'Found '.$toFind.' at position '.$pos."\n"; $start = $pos+1; // start searching from next position. } 

Output:

Found foo in position 1
Found foo at position 8

+16
source share

Using:

 while( ($pos = strpos(($str),$toFind,$start)) != false) { 

Explenation: Set ) after false for $start) , so $pos = strpos(($str),$toFind,$start) is placed between () .

Also use != false because php.net says: 'This function can return Boolean FALSE , but can also return a non-zero value that evaluates to FALSE , for example 0 or "" . Please read the Booleans section for more information. Use the === operator to check the return value of this function.

+5
source share
 $string = '\n;alskdjf;lkdsajf;lkjdsaf \n hey judeee \n'; $pattern = '\n'; $start = 0; while(($newLine = strpos($string, $pattern, $start)) !== false){ $start = $newLine + 1; echo $newLine . '<br>'; } 

This works outside the gate and does not start an infinite loop, as shown above, and the == == symbol allows a match at position 0.

+3
source share
 $offset=0; $find="is"; $find_length= strlen($find); $string="This is an example string, and it is an example"; while ($string_position = strpos($string, $find, $offset)) { echo '<strong>'.$find.'</strong>'.' Found at '.$string_position.'</br>'; $offset=$string_position+$find_length; } 
+1
source share

All Articles