bpops Posted March 27, 2008 Share Posted March 27, 2008 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 More sharing options...
kenrbnsn Posted March 27, 2008 Share Posted March 27, 2008 Are you always taking the first word of the string or only under certain circumstances? Ken Link to comment https://forums.phpfreaks.com/topic/98098-making-the-xxxx-into-xxxx-the/#findComment-501879 Share on other sites More sharing options...
bpops Posted March 27, 2008 Author Share Posted March 27, 2008 Only if it's "A", "The", or "An" (think the words that are ignored in general when alphabetizing something). Link to comment https://forums.phpfreaks.com/topic/98098-making-the-xxxx-into-xxxx-the/#findComment-501880 Share on other sites More sharing options...
bpops Posted March 27, 2008 Author Share Posted March 27, 2008 I figured it out.. if (strpos($var,'The') === 0) checks that these are the same type, too, so while it's true that FALSE == 0, it's NOT true that FALSE ===0.. my head exploded. Link to comment https://forums.phpfreaks.com/topic/98098-making-the-xxxx-into-xxxx-the/#findComment-501887 Share on other sites More sharing options...
kenrbnsn Posted March 27, 2008 Share Posted March 27, 2008 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 Link to comment https://forums.phpfreaks.com/topic/98098-making-the-xxxx-into-xxxx-the/#findComment-501896 Share on other sites More sharing options...
bpops Posted March 27, 2008 Author Share Posted March 27, 2008 That's a much cleaner method. I'll try this out, thanks Ken! Link to comment https://forums.phpfreaks.com/topic/98098-making-the-xxxx-into-xxxx-the/#findComment-501900 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.