0

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);
?>

2
Contributors
1
Reply
8
Views
3 Years
Discussion Span
Last Post by cereal
0

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().

Edited by cereal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.