Matching Quote Content

I am trying to remove quotes from a string. Example:

"hello", how 'are "you" today'

returns

hello, how are "you" today

I am using php preg_replace.

At the moment, I have several solutions:

(\'|")(.*)\1

The problem with this is that all characters (including quotation marks) in the middle match, so the result ($ 2) is

hello", how 'are "you today'

Backlinks cannot be used in character classes, so I can't use something like

(\'|")([^\1\r\n]*)\1

not to match the first backlink in the middle.

The second solution:

(\'[^\']*\'|"[^"]*")

The problem is that this includes quotes in the backlink, so it actually does nothing. Result ($ 1):

"hello", how 'are "you" today'
+3
source share
3 answers

Instead:

(\'[^\']*\'|"[^"]*")

Just write:

\'([^\']*)\'|"([^"]*)"
  \______/    \_____/
     1           2

Now one of the groups will correspond to the cited content.

, , , , , $1$2, ( ), .

PHP ( ideone.com):

$text = <<<EOT
"hello", how 'are "you" today'
EOT;

print preg_replace(
  '/\'([^\']*)\'|"([^"]*)"/',
  '$1$2',
  $text
);
# hello, how are "you" today 

1 2 ( ). ( ).

:

(  1[^1]*1  |  2[^2]*2  )
\_______________________/
   capture whole thing
   content and quotes

, ( , ), .

(, , ), : .

1([^1]*)1  |  2([^2]*)2
 \_____/       \_____/
 capture contents from
each alternate separately

1, 2 , , . "" , , .. 1 , 1.


[…] - . - [aeiou] . [^…] . [^aeiou] , .

(…) . (pattern) - . (?:pattern) .

+3

:

, -

(\'|")([^\1\r\n]*)\1
(\'|")(((?!(\1|\r|\n)).)*)\1

( (?!...) - ...), .

, , " , backref".

Edit:

, .

+2

. ( )

  • , ""
  • "" , ,

, , , . , , , .

XML-.

0

Source: https://habr.com/ru/post/1761409/


All Articles