Domanda

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...

È stato utile?

Soluzione

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"

Altri suggerimenti

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

Of course, this will remove all quotation marks, even from inside the strings. Is this what you want? How many strings like this are there?

The question was on how to do it with a regex (maybe for curiosity/learning purposes).

This is how you would do that in php:

$result = preg_replace('/(")(.*?)(")/i', '$2', $subject);

Hope this helps, Buckley

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