How can the preg_match_all function be used to find all positions of a substring within a string in PHP?

To find all positions of a substring within a string in PHP, you can use the preg_match_all function with the PREG_OFFSET_CAPTURE flag. This flag will return the offset (position) of each match in the original string. By using this function, you can easily retrieve all positions of the substring within the string.

$string = "Hello, this is a sample string with sample text.";
$substring = "sample";
preg_match_all('/' . preg_quote($substring, '/') . '/', $string, $matches, PREG_OFFSET_CAPTURE);

foreach ($matches[0] as $match) {
    echo "Position: " . $match[1] . "\n";
}