Q:

Replace text in the Title

In a string displayed by <?php the_title(); ?> I have to replace all & characters with and.
Here is the code I've tried without success:
<?php $wptitle = the_title(); $wptitle = str_replace('&', 'and', $wptitle);?><?php echo $wptitle; ?>

The full code to be replaced: 
<h2><a href="<?php if(get_post_meta($post->ID, 'links_link_custom', true)): ?><?php echo get_post_meta($post->ID, 'links_link_custom', true) ?><?php else: ?><?php the_permalink(); ?><?php endif; ?>"><?php the_title(); ?></a></h2>

A:

First things first, lets clean up your code:
<?php $wptitle = the_title(); $wptitle = str_replace('&', 'and', $wptitle);?><?php echo $wptitle; ?>

Lets remove the PHP tag spam and put things in nice clean lines:
<?php
$wptitle = the_title();
$wptitle = str_replace('&', 'and', $wptitle);
echo $wptitle;
?>

Now if we look at the problem, the_title, that function outputs the title and doesn't return anything. This means $wptitle is empty, so your string replace does nothing.
You need to tell it to return it or it won't know, computers aren't the same as people, they need to be told explicitly what to do with no assumptions.
However, a quick google for the_title brings up the codex as the first entry, along with a related function get_the_title which would solve your problem. Reading the documentation says that these are the arguments this function takes:
<?php the_title( $before, $after, $echo ); ?>

So you can change $wptitle = the_title(); to this:
$wptitle = the_title( '','',false );

Or this:
$wptitle = get_the_title();

There is also a much better method that you can use involving filters:
add_filter( 'the_title', 'drabello_swap_ampersands' );
function drabello_swap_ampersands( $old_title ) {
    $new_title = // do the replacement..
    return $new_title;
}

