-1

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

hizki
  • 709
  • 1
  • 8
  • 19

3 Answers3

5

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"

Paul
  • 139,544
  • 27
  • 275
  • 264
1
$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?

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
  • Unless the text between the outer quotes contains escaped quotes ... then you're in trouble :-) – keithhatfield Mar 20 '12 at 14:51
  • True. I think $output = trim($input, '"'); as @PaulR.P.O. suggested may be better, but it's not clear from the question exactly what the use case is. – Matt Gibson Mar 20 '12 at 14:57
0

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

buckley
  • 13,690
  • 3
  • 53
  • 61
  • Why bother with `/i` when the expression contains no alphas? – DaveRandom Mar 20 '12 at 15:12
  • Also why bother with capturing the `"`'s and it's also incorrect because you used non-greedy matching. You need to remove the `?` from your expression. Greedy matching is wanted here. – Paul Mar 20 '12 at 15:59