2

We have strings in php like the following two examples:

{{'LANGUAGE_ID','String inclusive special chars (,/)'}}
{{'LANGUAGE_ID','String inclusive special chars (,/)','Another string inclusive special chars (,/)'}}

The strings are always surrounded by {{ and }}. Inside we have multiple elements separated by a comma and surrounded by single quotes. The first element is always a word \w. After that we have a unknown number of elements which can be a word or sentence including special characters. What we want to get is the content (text between single quotes) for each element.

We have a solution as long as we know how many elements the string contains.

Solution for 1. example: {{'([\w]+)','([^\n\r']+)'}}

Solution for 2. example: {{'([\w]+)','([^\n\r']+)','([^\n\r']+)'}}

We are looking for a solution which works for both examples or even a example with three or more elements.

We have a regex share to play around here: http://regexr.com/3c58c

2 Answers 2

2

You can use this regex using \G:

preg_match_all('/(?:{{|\G,)'([^']+)'(?=.*?}})/', $text, $matches);

print_r($matches);

RegEx Demo

Sign up to request clarification or add additional context in comments.

4 Comments

\R matches a capital R. I don't think it's necessary. Works with just (?:{{|\G,)'([^\']+)'(?=.*?}}) - Perhaps he was attempting to do a return? \r?
Mike is right, \R is not even needed here. See updated answer. btw \R matches any newline character but it shouldn't be used in [...]
it does work. Thanks. But to be honest I don't understand the \G, would you be so kind and give me a short explanation?
\G assert position at the end of the previous match or the start of the string for the first match. So in our example it matches position after {{ then after '([^']+)' match it matches comma after that match and it keeps on matching that until it gets }}
0

How about this one:

{{'([\w]+)',('([^\n\r']+)',*)*}}

3 Comments

I just copied and pasted it into my regexr link and it doesn't look correct
With this expression, both lines in regexr are highlighted
This has been flagged as low quality. Please edit your answer and explain each of the steps in it.

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.