Question

I am new to PHP and I have the below code and I basically wish to find all keywords enclosed between

'<#' and '#>'

sample code:

<?php

$subject = "askdbvbaldjbvasdblasdbvl<#2134#>cbkdbskbkabdvb<#213aca4#>";
$pattern = "/(?<=\<\#)(.*?)(?=\#\>)/";
preg_match_all($pattern, $subject, $matches);
echo '<pre>',print_r($matches,true),'</pre>';

?>

now i am expecting a value array like:

Array
(
    [0] => Array
        (
            [0] => 2134
            [1] => 213aca4
        )
)

But i am getting and output like:

Array
(
    [0] => Array
        (
            [0] => 2134
            [1] => 213aca4
        )

    [1] => Array
        (
            [0] => 2134
            [1] => 213aca4
        )

)

can any one tell me why am i getting the second array and how can i get rid of that..

Was it helpful?

Solution

The second array contains the sub-match, or matched group, because you're using a capture group.

Simply remove the parens in your regex:

$pattern = "/(?<=\<\#).*?(?=\#\>)/";

Also, you should be able to use this regex without some escapes:

$pattern = "/(?<=<#).*?(?=#>)/";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top