M
M
Maxim Medvedev2016-11-23 11:51:58
PHP
Maxim Medvedev, 2016-11-23 11:51:58

How to do a semicolon replacement in a string inside quotes?

Hello,
I have a csv file with the following format:

текст текст; "текст в двойных кавычках; текст в двойных кавычках; текст в двойных кавычках"; текст; текст
текст текст; "текст в двойных кавычках; текст в двойных кавычках; текст в двойных кавычках"; текст; текст
текст текст; "текст в двойных кавычках; текст в двойных кавычках; текст в двойных кавычках"; текст; текст

Through fgetcsv I got an array of the form:
Array
(
[0] = > текст текст; "текст в двойных кавычках; текст в двойных кавычках; текст в двойных кавычках"; текст; текст
[1] = > текст текст; "текст в двойных кавычках; текст в двойных кавычках; текст в двойных кавычках"; текст; текст
)

Now you need to break each element by semicolon, but since this character also occurs inside the string inside quotes, I ran into a problem, how to do this? You need to replace only inside quotes.
I know it's a regex, but Google couldn't help with an example.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Medvedev, 2016-11-25
@reimax

Actually solving the problem:

$string = preg_replace_callback(
        '/"(.*)"/U',
        function ($matches) {
          return str_replace(";", ",", $matches[0]);
        },
        $string
      );

A
Alexey Ukolov, 2016-11-23
@alexey-m-ukolov

fgetcsv - Read a line from a file and parse the CSV data

fgetcsv() takes the used delimiter as an argument and does everything itself. By default, a comma is assumed as a separator, you need to specify that you have a semicolon.

S
sts, 2016-11-23
@stunoff

https://regex101.com/r/7Li7Oi/1
maybe this will work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question