Jump to content

[SOLVED] PHP string conversion: "The Matrix" to "Matrix, The"


mejpark

Recommended Posts

Good evening folks,

 

I have a webapp that allows users to catalogue their DVD titles, and I would like to reformat all titles that start with the word "the".

 

Specifically, if the 'title' string starts with the word "the", I want to chop "the" from the beginning of the string, prepend it with a comma and a space, and then glue it onto the end of the string:

 

"The Matrix" (current)

 

"Matrix, The" (desired)

 

What is the easiest way to do this in PHP?

 

Regards,

 

Mike

 

function changeTitle($title)
{
$parts = explode(' ', $title);
return $parts[1] . ', ' . $parts[0];
}

$title = 'The Matrix';
$new_title = (strtolower(substr($title, 0, 3)) == 'the') ? changeTitle($title) : $title;

echo $new_title;

Output: Matrix, The

 

However, that won't work for titles that contain more than 3 words and the word 'the'. How would you want want the title to change if it was like 'The something something'? I can change the function for you if necessary.

Explode has an optional 3rd parameter that when set to 1 would handle exploding at just the first space.

Ahh, I never knew that :P

 

Use this then:

 

function changeTitle($title)
{
$parts = explode(' ', $title, 2);
return $parts[1] . ', ' . $parts[0];
}

$title = 'The Matrix';
$new_title = (strtolower(substr($title, 0, 3)) == 'the') ? changeTitle($title) : $title;

echo $new_title;

 

If the title was 'The Matrix' it would output Matrix, The . If it was 'The Matrix Reloaded' it would output Matrix Reloaded, The.

 

Edit: The third parameter in explode() doesn't work like that..

 

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .

 

So it had to actually be 2.

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.