Cidwel
Cidwel

Reputation: 45

Regex for getting specific groups

I need a regex syntax for getting specific groups in a string that are delimited with the '%' charavter. I have this string as example:

%David davidson%Hello I can store 1000 numbers too%anotherchain%how are you!?%

I want to store in different PHP variables those matches like this

$var1 = david davidson;
$var2 = Hello I can store numbers;

... etc

but I don't know how to get a specific group of characters (per example get the second match that doesn't start with a symbol or with a % symbol)

I tried with this code %.*?(%) but it only returns the first and the third match but I actually want to select specific groups

I searched it on google and here but I didn't found an answer that fits a little with what I need, probably because I don't know the keywords I need to search to get a good answer

Upvotes: 0

Views: 68

Answers (1)

Brend
Brend

Reputation: 196

You can use

preg_match_all('/[^%]+/sim', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
print_r($result);

This will give you:

  • David davidson
  • Hello I can store 1000 numbers too
  • anotherchain
  • how are you!?

    [^%]+

This means in regex, every char except "%"

Upvotes: 2

Related Questions