2

I have a problem with a regular expression.
I'm working with tokens and I have to parse a text like this:

Just some random text
#IT=AB|First statement# #xxxx=xxx|First statement|Second statement#
More text

I use preg_replace_callback since I have to use the first statement or the second one, depending on the first expression is true or not; it's a sort of IF...ELSE... statement.

What I expect are 2 elements like this:

#IT=AB|First statement# 
#xxxx=xxx|First statement|Second statement#

So I can start manipulating them inside my callback function.
I tried with this regex /#.*#/, but i get the entire string, it's not parsed into elements.

How can I achieve that? I'm sorry but regex aren't my thing :(

1 Answer 1

4

The quantifier * is greedy by default. So a .* will match as much as it can and as a result it'll match a # as well. To fix this you can make the * non-greedy by adding a ? after it. Now a .*? will try to much as little as it can.

/#.*?#/

or you can look for only non # characters between two #:

/#[^#]*#/
Sign up to request clarification or add additional context in comments.

2 Comments

it works! thanks a lot. Please, can you explain me where was the error?
.* is greedy, matching as much as possible (including any #s it finds along the way). .*? matches as few characters as possible, [^#]* matches any characters except hashes.

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.