Search code examples
phpregexquotations

Extract text from quotation marks in PHP


I have a PHP page which gets text from an outside source wrapped in quotation marks. How do I strip them off?
For example:

input: "This is a text"
output: This is a text

Please answer with full PHP coding rather than just the regex...


Solution

  • This will work quite nicely unless you have strings with multiple quotes like """hello""" as input and you want to preserve all but the outermost "'s:

    $output = trim($input, '"');
    

    trim strips all of certain characters from the beginning and end of a string in the charlist that is passed in as a second argument (in this case just "). If you don't pass in a second argument it trims whitespace.

    If the situation of multiple leading and ending quotes is an issue you can use:

    $output = preg_replace('/^"|"$/', '', $input);
    

    Which replaces only one leading or trailing quote with the empty string, such that:

    ""This is a text"" becomes "This is a text"