Jump to content

[SOLVED] preg_replace to strip front and add to end


techtheatre

Recommended Posts

i have written a script that allows me to track my DVD collection. I type in the title and some other info and it all gets stored in a MySQL database on my webserver. Everything is written in PHP4. I have a problem with alphabetization when i pull out the results, because many titles start with A, AN, or THE. I am trying to use preg_replace to detect if the title string starts with one of these three (followed by a space) and if so, strip it off the front and append it to the end with a comma and space. I plan to modify the title string before i insert the info into my database. I know there is an easy way to do this whole thing in one statement, but i cannot seem to get it figured out. Here is some info:

if i start with the following:
$MovieTitle = "The Matrix"

$MovieTitle = preg_replace(SOMETHING HERE);

i want to end with the following:
$MovieTitle == "Matrix, The"

(same thing for "An " or "A ")

Any help with what to put for my preg_replace line is greatly appreciated.
THANKS!
[code]
<?php
$tests = array(
'The Matrix',
'Fight Club',
'Wallace & Gromit: The Curse of the Were-Rabbit',
'A Tale of Two Cities',
'An Inconvenient Truth'
);
foreach ($tests as $test) {
echo $test, ' => ';
$test = preg_replace('/^(An?|The)\s+(.+)/', '\2, \1', $test);
echo $test, '<br>';

}
?>
[/code]
:D
This works PERFECTLY!  THANKS!  I understand the search string part (i had figured that part out on my own)...but can you explain what part of this is doing the text replacement?  I have looked at this and simply don't understand what it is doing (but it certainly does it efficiently).  Really, the part i don't follow is:
\s+(.+)/', '\2, \1'

Anyway, if you can explain what is going on that is awesome...but if not i am just very greatful that you helped!  I am so glad this works!  THANK YOU!!!
\s+ gobbles up one or more instances of whitespace.
(.+) captures the rest of the text.

Since parentheses capture text--the first set is stored in \1, the second in \2, and so on--you simply output them in reverse, adding the comma.

See the links in my signature for more information.
Thanks!  That REALLY helps.  Maybe i can finally begin to understand this function now.  I know that you can do all sorts of very power ful things with preg_replace...and i have always wanted to use it efficiently, and i think this really helped me in that direction.  You are awesome.  Thanks for your help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.