0% found this document useful (0 votes)
43 views

PHP Tizag Tutorial-72

The document demonstrates using the strpos() function in PHP to find the position of substrings within a string. It first shows finding the position of the first and second occurrence of "5" in a string. It then shows using a while loop with strpos() to find the position of every occurrence of "5" in the string, incrementing a counter each time. The loop uses an offset to start searching after the last match each iteration.

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

PHP Tizag Tutorial-72

The document demonstrates using the strpos() function in PHP to find the position of substrings within a string. It first shows finding the position of the first and second occurrence of "5" in a string. It then shows using a while loop with strpos() to find the position of every occurrence of "5" in the string, incrementing a counter each time. The loop uses an offset to start searching after the last match each iteration.

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

PHP Code:

$numberedString = "1234567890123456789012345678901234567890";

$fivePos = strpos($numberedString, "5");


echo "The position of 5 in our string was $fivePos";
$fivePos2 = strpos($numberedString, "5", $fivePos + 1);
echo "<br />The position of the second 5 was $fivePos2";

Display:
The position of 5 in our string was 4
The position of the second 5 was 14

By taking the first match's position of 4 and adding 1 we then asked strpos to begin searching after the last
match. The string it was actually sesarching after computing the offset wa: 6789012345... Letting us find the
second 5 in the string.
If we use our knowledge of PHP While Loops we can find every single 5 in our string numberedString with
just a few lines of code.

PHP Code:
$numberedString = "1234567890123456789012345678901234567890";
$offset = 0; // initial offset is 0
$fiveCounter = 0;

while($offset = strpos($numberedString, "5", $offset + 1)){


$fiveCounter++;
echo "<br />Five #$fiveCounter is at position - $offset";
}

You might also like