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? Quote Link to comment 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 Quote Link to comment 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). Quote Link to comment 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. Quote Link to comment 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 Quote Link to comment 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! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.