Mike Q
Mike Q

Reputation: 7357

Get string between single or double quotes

I am getting the string data in between single or double quotes in the following code. Is it possible to combine this into a single command or simplify ?

Examples:

 STR_NAME = '12345'
 STR_NAME = "12345"

Code:

$match = "STR_NAME = '12345'";
if (preg_match('/"([^"]+)"/', $match, $m)) {
    $val = $m[1]; //found string in double quotes
  } else {
    if (preg_match("/'([^']+)'/", $match, $m)) {
      $val = $m[1]; //found string in single quotes
    }
  }

Output:

 echo $val;
 12345

Upvotes: 1

Views: 192

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

You could use a a capturing group with a character class (["']) to match either ' or " and a backreference to group 1.

To match what is in between you can use .+? to match at least 1 character.

The value is in capture group 2

(["'])(.+?)\1
  • (["']) Capture group 1 (For the backreference)
  • (.+?) Match 1+ times any char except a newline
  • \1 Backreference to group 1

Regex demo

Note that you don't have to escape the ' in the character class.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 79024

Use a backreference \1 to the first quote found:

preg_match('/(["\'])([^\1]+)\1/', $match, $m);
echo $m[2];
  • (["\']) Match and capture in group 1 " or '
  • ([^\1]+) Match and capture in group 2 one or more not ^ what was captured in group 1
    • You can use many things here that don't match the following quote like (.+?)
  • \1 Match what was captured in group 1 " or '

Would not match something like STR_NAME = "1234'.

If the data is consistent and predictable then you might be able to get away with:

["\']([^"\']+)["\']

Or:

["\'](.+?)["\']

Upvotes: 2

Related Questions