문제

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

도움이 되었습니까?

해결책

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"

다른 팁

$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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top