0

If I use preg_split() function for example:

$string = 'products{id,name},articles{title,text}';
$arr = preg_split('/\}\,(\w)/', $string);
print_r($arr);

I receive the following result:

Array ( [0] => products{id,name [1] => rticles{title,text} )

How to receive full word articles i.e. to extract the value of the regex pattern ?

ps. If it's possible at all

2
  • 1
    Might be a good idea here to give an example of what you are entering and what you expect to get back. Commented Aug 25, 2020 at 10:23
  • The string I'm entering is in my question. As you see now I receive rticles but I want to extract also regex value a and add it before the rticles Commented Aug 25, 2020 at 10:25

1 Answer 1

1

You could split on matching the curly braces, clear the match buffer. Then match the comma and use a positive lookahead to assert a word character on the right instead of matching it.

{[^{}]*}\K,(?=\w)

The pattern matches:

  • { Match {
  • [^{}]* match 0+ times any char except { and }
  • } Match }
  • \K, Forget what is matches until now and match a comma
  • (?=\w) Positive lookahead, assert what is directly to the right is a word character

Regex demo | Php demo

$string = 'products{id,name},articles{title,text}';
$arr = preg_split('/{[^{}]*}\K,(?=\w)/', $string);
print_r($arr);

Output

Array
(
    [0] => products{id,name}
    [1] => articles{title,text}
)
Sign up to request clarification or add additional context in comments.

Comments

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.