Can’t you pass limit number of replacements in str_replace? Like that
$text = str_replace(array_keys($replace), $replace, $text, 1);
EDIT:
Sorry I was thinking about something else and missed this one. You can use preg_replace and set limit in it. Like this one.
function wp_affiliate_links($text){
$replace = array(
'/ nursery rhymes /' => ' <a href="http://www.nurseryrhymes.me/">nursery rhymes</a> ',
'/ poems /' => ' <a href="http://www.nurseryrhymes.me/">poems</a> ',
'/ rhymes /' => ' <a href="http://www.nurseryrhymes.me/">rhymes</a> ',
);
$text = preg_replace( array_keys($replace), $replace, $text, 1 );
return $text;
}
add_filter('the_content', 'wp_affiliate_links');
add_filter('the_excerpt', 'wp_affiliate_links');
EDIT 2:
Try this one.
function wp_affiliate_links($text){
$replace = array(
'/ nursery rhymes /' => ' <a href="http://www.nurseryrhymes.me/">nursery rhymes</a> ',
'/ poems /' => ' <a href="http://www.nurseryrhymes.me/">poems</a> ',
'/ rhymes /' => ' <a href="http://www.nurseryrhymes.me/">rhymes</a> ',
);
foreach ( $replace as $key ) {
$text = preg_replace( array_keys($replace), $replace, $text, 1 );
return $text;
}
}
add_filter('the_content', 'wp_affiliate_links');
add_filter('the_excerpt', 'wp_affiliate_links');