문제

I am attempting to modify book titles with preg_replace() for alphabetization in the way a library would handle book titles; Moving the words "the", "a", and "an" from the beginning of the title to the end of the title.

For my example, I am using the book title "The Final Book Title" and would like that title modified to "Final Book Title, The" so that a book actually titled "Final Book Title" would be sorted correctly in relation to the book in my example.

preg_replace('/^(the |a |an )(.*?)/i', '$2, $1', 'The Final Book Title');

The code above results in the string: , The Final Book Title

I am clearly misunderstanding the use of backreferences, but can't figure out why.

Thanks!

도움이 되었습니까?

해결책

Remove the ? in .*?, you don't want it to be lazy.

Adding a ? to a quantifier makes it lazy, which roughly means that it will match the least amount possible while the overall regex still returning a match.

You have no anchor at the end, so when .*? matches the least amount possible (because of laziness), it matches, well, nothing. Your whole regex only matches The.

This should do the trick

preg_replace('/^(the|an?) (.*)/i', '$2, $1', 'The Final Book Title');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top