0

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.

11
  • Not clear what you're trying to do but I don't think you need a regex for that. Commented Sep 8, 2023 at 6:39
  • The input and output data are not clear. Commented Sep 8, 2023 at 6:47
  • I want to put double quote (") to the numbers only if they don't already have one. Commented Sep 8, 2023 at 6:59
  • 1
    Why not just $data[21] .= '"' inside the if? Commented Sep 8, 2023 at 7:00
  • And why did you put the arrays tag? Commented Sep 8, 2023 at 7:06

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much Nick. After testing and still got some unwanted results, I found out some of the data were bad. Instead of double quote, they have 2 single quotes. For example the bad 14" was written 14'' initially. That's why both my original question and this solution did not work at first. Sorry for false question and thank you again for your help, so I can realized this. Cheers..!!
@Pekzz ah, what a pain - on a non fixed-width font they would look pretty similar. Anyway, I'm glad this was helpful. Note (in case it wasn't clear) that with this code you don't need the if (!str_contains($data[21], '"')) statement.
wow.. I didn't know this doesn't need "if". Thanks for pointing this out. I'll use this instead.
@Pekzz note you can even deal with the two single quotes problem: 3v4l.org/24OvM

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.