Jump to content

preg_match_all doesn't work properly


Full-Demon

Recommended Posts

Hi,

 

When I have a subject and search for a certain character in it (where the character before and after that character has certain conditions) it doesn't gives me the right output.

 

preg_match_all('/(\W|\A)(\=)(\W|\Z)/', 'blahblah == lala', $matches);

 

Result:

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

[some more sub arrays here]
)

 

This code checks for the character '=' and gets the surrounding characters too.

The first character is matched alright (' =='), but the second one not (' = ') (note the spaces). The second result should be ('== ').

 

Why does the second result ignores the first '='? And how to fix this?

 

Thanks in advance,

 

FD

Link to comment
Share on other sites

Once something is matched the engine continues to move forward. You can utilize offsets and \G to tell it where to start. I'm not sure how efficient this is, but to my knowledge it's the only way to pull it off in PHP:

 

<pre>
<?php
$str = 'blahblah == lala';

$offset = 0;
$str_len = strlen($str);
while ($offset < $str_len) {
	if (preg_match('/\G(\W|\A)(=)(\W|\Z)/', $str, $matches, NULL, $offset)) {
		print_r($matches);
	}
	++$offset;
}
?>
</pre>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.