RegEx: Match nth occurrence

You can use this regex:

\b_name=(?:[^"]*"){3}

RegEx Demo

RegEx Details:

  • \b_name: Match full word _name:
  • =: Match a =
  • (?:[^"]*"){3}: Match 0 or more non-" characters followed by a ". Repeat this group 3 times.

If want to match everything between the first and the third(!) double quote (the third isn't necessarily the last, you told), you can use a pattern like this:

$string = '_name=foo"bar"test" more text"';
// This pattern will not include the last " (note the 2, not 3)
$pattern = '/_name=((.*?"){2}.*?)"/';

preg_match($pattern, $string, $m);
echo $m[1];

Output:

foo"bar"test

Original answer:

I'm not sure if I got you correctly, but it sounds like you want to perform a so called greedy match, meaning you want to match the string until the last " regardless whether the string contains multiple "s.

To perform a greedy match, just drop the ?, like this:

_name=(.*)"

You can try it here: https://regex101.com/r/uC5eO9/2

Tags:

Regex

Pcre