PHP preg_replace double quote not working

43 Views Asked by At

I loaded a csv to array. And I want to put " to column 21 if they don't have yet. This is sample of column 21. Some are empty. It's $data[21] in my case.

21
14"
14"
14"
empty
16"

This is my code

if (!str_contains($data[21], '"')) {
$data[21] = preg_replace('/[0-9]+/',$data[21].'"',$data[21]);
}

But the result is

21"
14"
14''"''
14''"''
empty
16''"''

Only the first two and the empty ones are correct. What's wrong with this? Thanks.

EDIT.. Please read comment

After helps from everyone, I realized some of the data was actually bad. They use 2 single quotes instead of double quotes. So actually this code works, as well as suggestions from Nick. Thanks.

1

There are 1 best solutions below

4
Nick On BEST ANSWER

You can use preg_replace with the following regex:

(?<=\d)$

which will match end-of-string when it is preceded by a digit. In PHP:

$data[21] = preg_replace('/(?<=\d)$/', '"', $data[21]);

Demo on 3v4l.org

Based on your sample data, I've assumed the values are made up of digits. If not, then you need to check that what precedes end-of-line is not a " or beginning of line, which you can do with this regex:

(?<!"|^)$

Demo on 3v4l.org

In both cases, for your sample data the output is:

21"
14"
14"
14"

16"