1

I have this array:

'@(.*?)<div>(.*?)</div>(.*?)@i' => 'ok'

And I am using preg_replace to return the value "ok" from some string.

The problem is that when I do the preg_replace, the last (.*?) isn't "detected".

Example

I have the string: test1<div>test2</div>test3

And with that array and preg_replace, it would return oktest3. Why isn't test3 replaced?

1 Answer 1

4

The problem is, that .*? is a non-greedy match, and thus tries to match as little as possible.

If you want it to match from the beginning and to the end of the string, use a ^ and $ to anchor the regex to the beginning and end, like so:

'@^(.*?)<div>(.*?)</div>(.*?)$@i' => 'ok'
Sign up to request clarification or add additional context in comments.

2 Comments

@AfonsoMatos: Happy to help. Remember to accept my answer, if you feel it solves your problem. I can recommend checking out regular-expressions.info - it's a pretty good source of information.
Ok, thx for the website. I didn't accept it yet, because I get some error telling me to try in 6 minutes..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.