basically Im searching for the term ded within subject,
how come all i get is Array() when i run this

<?php
$subject = "dedfd";
$pattern = '/ded/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 2);
print_r($matches);
?>

and then i tried to search for the letter d within subject

and i get

Array ( [0] => Array ( [0] => d [1] => 2 ) )

what does this mean ?

<?php
$subject = "dedfd";
$pattern = '/d/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 2);
print_r($matches);
?>

Hi, in practice it happens that because of the fifth argument 2, preg_match() will search the pattern after the second byte, counting from zero. So if your $subject is dedfd, with the offset the function starts to search from dfd.

If, for example, you change the string to abdedfd then the pattern is correctly found. To avoid this problem you can remove the last argument from the preg_match() function and let return the position, so:

$subject = "asddedfd";
$pattern = '/ded/';

preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);

Outputs:

Array
(
    [0] => Array
        (
            [0] => ded
            [1] => 3
        )

)

Where [1] => 3, i.e. $matches[0][1], is the starting position of your searched string, the same result that you can get from strpos().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.