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 the output I need??
The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive.
strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently.
Using str_contains. The str_contains is a new function that was introduced in PHP 8. This method is used to check if a PHP string contains a substring. The function checks the string and returns a boolean true in case it exists and false otherwise.
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 "&foobar"
// as & is replaced by &. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With