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

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.