Search code examples
regexpreg-match

How to extract text that is inside quotes with regex or preg_match?


I receive as text the following string:

We have a new FB Leads "Puente Middleware".

The theme that I tried to extract the string with preg_match but it only returns the text that is outside the quotes and not inside.

$getSubject = preg_match('/"([^"]*)"/', $subject);
return "We have a new FB Leads"

I want to return "Puente Middleware"


Solution

  • You specified a correct capture group, but you never accessed the replacement. Try this version:

    $subject = "We have a new FB Leads \"Puente Middleware\"";
    preg_match('/"([^"]*)"/', $subject, $results);
    echo $results[1];
    

    This prints:

    Puente Middleware