frosty
frosty

Reputation: 2649

Matching any characters that's not a plus sign

I'm trying to use regex to match any characters that's not a '+' in between the words 'begin', and 'end' but it's not matching for some reason. What am I doing wrong?

$content = "begin+text1+end begin text2 end";
$regex = "~begin(^\++?)end~";
preg_match_all($regex, $content, $matches);

print_r($matches);

Result:

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

Expected Result:

Array ( [0] => Array ( begin text2 end ) [1] => Array ( text2 ) )

Upvotes: 0

Views: 47

Answers (2)

l'L'l
l'L'l

Reputation: 47169

If you change your pattern slightly you should get the expected result:

(?=[^\s\d]+)begin([^+\n]+)end

This pattern uses a positive lookahead - asserting that space or digit will be inversely matched before the word begin. The capture group then grabs anything between that and end which doesn't contain a + or line break \n.

Result:

Array ([0] => begin text2 end)[1] => Array([0] =>  text2))

Example:

https://regex101.com/r/qS6iL1/2

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You need to put the anchor ^ within a character class to create a negated character class:

"~begin([^+]+)end~"

Upvotes: 2

Related Questions