开发者

Find multiple string positions in PHP

I`m writing a PHP page that parses given URL. What I can do is find the first occurrence only, yet when I echo it, I get another value rather than the given.

this is what I did till now.

<?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 a loop can be used, yet I don`t know the condition neither the body of the loop would be.

And how can I show 开发者_Go百科the output I need??


This happens because you are using strpos on the htmlspecialchars($str) but you are using substr on $str.

htmlspecialchars() converts special characters to HTML entities. 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 haystack in both the functions.

To answer you other question of finding all the occurrences of one string in other, you can make use of the 3rd argument of strpos, offset, which specifies where to search from. 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 at position 1
Found foo at position 8


Use:

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

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

Also use != false, because php.net says: 'This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.


$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 out of the gate, and doesn't run an infinite loop like the above, and the !== allows for a match at position 0.


$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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜