Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ifrit's avatar
Level 2

Replacing /n in query

I have a query that looks like this

$query = DB::select(
    "
         SELECT
            p.id,
            p.name,
            regexp_replace('/\s\s+/', ' ', p.description) as description,
        FROM public.products p
        ORDER BY sort ASC
    "
)

but when I run it my output has replaced my description with /\s\s+/. What I need is for my query to replace /n with a space

0 likes
11 replies
Tray2's avatar

Can you show an example string and the expected result?

Ifrit's avatar
Level 2

yep.

example string

This is an\nexample string

expected result

This is an example string
Tray2's avatar

Try this

SELECT
            p.id,
            p.name,
            regexp_replace(p.description, '\\n', ' ') as description,
        FROM public.products p
        ORDER BY sort ASC
sr57's avatar
SELECT
            p.id,
            p.name,
            REPLACE(description, chr(13), ' ') as description,
        FROM public.products p
        ORDER BY sort ASC
Tray2's avatar

You don't need to use regexp either you can just

SELECT
            p.id,
            p.name,
            replace(p.description, '\n', ' ') as description,
        FROM public.products p
        ORDER BY sort ASC
Ifrit's avatar
Level 2

I'm still getting \n. Do you think that it might be because I'm trying to export it to an excel file? and that is why it isn't working?

Tray2's avatar

You need to do \\n and not just \n

sr57's avatar

You are still getting \n with my example?

SELECT
            p.id,
            p.name,
            REPLACE(p.description, chr(13), ' ') as description,
        FROM public.products p
        ORDER BY sort ASC

It does not depend of your export

sr57's avatar

Ok , it beacause \n is chr(10) ! -)

SELECT
            p.id,
            p.name,
            REPLACE(p.description, chr(10), ' ') as description,
        FROM public.products p
        ORDER BY sort ASC

Please or to participate in this conversation.