Domanda

I am trying to match a string using two different patterns to work together.
My source string is something like this:

Text, white-spaces, new lines and more text then ^^^^<customtag>

I need to get a group (the second one) that would capture one caret or none then a formatted HTML-like tag. So the first group would capture anything else.
It means that the string above should output this:

(Group 1)Text, white-spaces, new lines and more text then ^^^

(Group 2)^<customtag>

In the source string carets may be one, none or up to two thousands.
I need a good pattern that matches all those carets except the last one.
The code below is what I tried.

preg_match_all('/([\s\S]*\^*)(\^?<\w+>)$/', $string, $matches);


Please note: I used [\s\S] instead of the dot to match any character as well as white-spaces and new lines too.

È stato utile?

Soluzione

You may follow the below regex:

(?s)(.*)((\^|(?<!\^))<[^>]+>)

Live demo

PHP code:

preg_match_all('/(?s)(.*)((\^|(?<!\^))<[^>]+>)/', $string, $matches);

Altri suggerimenti

You can use as this:

preg_match_all('/(.*)((\^<[^>]*>)|([^\^]<[^>]*>))$/', $string, $matches);

See it working here: http://regexr.com?383g9

In this other link it is working fine: http://regex101.com/r/eQ3vV7

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top