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

geerizzle's avatar

Doing a sort/orderBy but ignoring an apostrophe at the start?

I want to sort data from my model in alphabetical order, but ignoring an apostrophe if it's at the start:

e.g. Alan 'Bob' Clare currently puts Bob at the start. How can I modify my query or sort on the collection to ignore apostrophes?

I thought this would work but it doesn't:

$items= $items->sortBy(function ($item) {return str_replace(''', '', $i['item']);});

0 likes
9 replies
MichalOravec's avatar

@geerizzle I think it could be

$items = $items->sortBy(function ($item) {
    return str_replace("'", '', $item->yourField);
});

Just replace yourField with your property.

willvincent's avatar

Before worrying about how to sort dirty data... why do you have dirty data in the first place?

jlrdw's avatar

Is Alan 'Bob' Clare 3 separate field, or one field?

And an ORDER BY will put Alan 'Bob' Clare before Bob White.

I do not see how 'Bob' is first unless you ORDER BY middle name.

And what is that sortBy? Just write an sql query and ORDER BY.

geerizzle's avatar

It's not dirty even if it looks like it, a few things need to be in quotes when they're output.

geerizzle's avatar

Three separate fields, I just put names for my examples, actually its:

Alanine

'Bad' Cholesterol

Cocaine

But the default orderBy puts 'bad' cholesterol at the top.

jlrdw's avatar
jlrdw
Best Answer
Level 75
 ORDER BY TRIM(BOTH "'" FROM yourfield)

If that doesn't work use the actual ascii for apostrophe.

1 like
geerizzle's avatar

Awesome, I went with: orderByRaw('TRIM(BOTH "\'" FROM name)')

Works perfect thanks

Please or to participate in this conversation.