Jump to content

Making 'The XXXX' into 'XXXX, The'


bpops

Recommended Posts

I want to change the format of titles of books and movies automatically from things such as

 

'A Book' and 'The Movie'

 

to

 

'Book, A' and 'Movie, The'

 

Currently, I'm trying something like

 

$var = 'The Movie';

if (strpos($var,'The') == 0){
  $var = substr_replace($var,'',0,strlen($var)-4).', The';
}

 

This works for 'The Movie' but if I give it anything at all, it still executs what's inside the if(). This is because if it finds The at the beginning, strpos returns 0, and if it doesn't find it at all, it still returns 0!

 

Any ideas -- a fix for this code, or a better solution alltogether?

Link to comment
https://forums.phpfreaks.com/topic/98098-making-the-xxxx-into-xxxx-the/
Share on other sites

Here's another solution. See if you can use it:

<?php
$tst = array('The Word','A Movie','Another Movie','An Animal','The Worst Movie Ever');
$wrds = array('the','a','an');
$new = array();
foreach($tst as $str) {
	$tmp = explode(' ',$str,2);
	if (in_array(strtolower($tmp[0]),$wrds))
		$new[] = implode(', ',array_reverse($tmp));
	else
		$new[] = $str;
}
echo '<pre>' . print_r($new,true) . '</pre>';
?>

 

Ken

 

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.