4

I want to remove quotes from specific fields where there is an integer between the quotes.

From this line : "AAA","99"

to this line : "AAA",99

This is my string :

$string='"name","99","email","112"';
Super Jade
  • 5,609
  • 7
  • 39
  • 61
PHPDEVLOPER
  • 161
  • 1
  • 10

2 Answers2

3

1) Split by ',' into a table. (I'm using string_split, which is supported in MSSQL 2016+ - there are many ways to implement split functions in earlier SQL versions.)
2) Use REPLACE(value, '"', '') and ISNUMERIC to figure out which values are numbers.
3) Use FOR XML PATH/STUFF to add the commas back.

DECLARE @str VARCHAR(25) = '"name","99","email","112"'

SELECT STUFF(
(
    SELECT ',' + 
        CASE 
            WHEN ISNUMERIC(REPLACE(value, '"', '')) = 1 
                THEN REPLACE(value, '"', '') 
            ELSE value 
        END
    FROM STRING_SPLIT(@str, ',')
    FOR XML PATH('')
), 1, 1, '')

Returns:

"name",99,"email",112
Arulkumar
  • 12,966
  • 14
  • 47
  • 68
Max Szczurek
  • 4,324
  • 2
  • 20
  • 32
  • if there is any function like getdate(),e.g. $string='"name","99","email","112","getdate()"'; i have to remove quotes from getdate , how to possible ? – PHPDEVLOPER Jul 19 '18 at 06:23
1
$string = '"name","99","email","112"';

$string = str_replace('"', '', $string);

$strings = explode(",", $string);

foreach($strings as $key => $string) {
    $strings[$key] = preg_match('/^[0-9]*$/', $string) 
        ? intval($string) : '"'.$string.'"';
}

$string = implode(",",$strings)
Jorj
  • 1,291
  • 1
  • 11
  • 32
  • if there is any function like getdate(),e.g. $string='"name","99","email","112","getdate()"'; i have to remove quotes from getdate , how to possible ? – PHPDEVLOPER Jul 19 '18 at 06:22