View Single Post
Old 03-10-2010, 05:24 PM   #5 (permalink)
delayedinsanity
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

There's a queen? Wait, are you talking about my wife? Depends on the time of month whether or not she likes being called that...

Anywho, it is fairly simple. Since you have the stop word you're searching for, you could easily use substr() to pull the first letter ( 0, 1 ) from the word, and the last ( -1 ), then use those on either end of $replace and reduce the str_repeat function by -2. This would take very little effort, and you'd still be zipping along with str_replace().

There's only one problem with this solution though. How do you maintain case if one of your words is found at the start of a sentence?

Okay, so str_replace isn't your best option anymore. Now preg_replace is your friend (use preg, forget ereg exists because PCRE > POSIX and it's deprecated anyways). Regular expressions frighten a lot of people but they really shouldn't - you can do generally useful things with the simplest of expressions most of the time.

php Code:
// The new and improved loop

            foreach ( $words as $word ) {
        $word = trim( $word );

        $pattern = '~(' . substr_replace( $word, ')' . substr( $word, 1, -1 ) . '(', 1, -1 ) . ')~^i';
        $replace = '$1' . str_repeat( '*', strlen( $word )-2 ) . '$2';

        $string = preg_replace( $pattern, $replace, $string );
    }

Simple enough, right? All we're doing is surrounding the first and last letter of the word with parentheses so that we can capture them and reuse them in the replacement string. So we're taking a word such as "lorem" and making it "(lorem)". Then using substr_replace() with a nested substr(), we're pulling "orem" out, and replacing it with ")orem(" so that what we're left with is "(l)ore(m)". You could alternatively just substr the first and last letter off into variables, then use them to do something such as;

php Code:
$first = substr( $word, 0, 1 );
$last = substr( $word, -1 );
$middle = substr( $word, 1, -1 );

$replace = "({$first}){$middle}({$last})" // without the regular expression delimiters and i modifier
 

It all depends on your personal preference. I prefer to avoid assigning variables I'm only going to use once. Other people find it more readable, and whatever works best for you is what you should do.

Okay. Ever heard of Simple:Press Forums? The nitwits who programmed it used tables and didn't even bother to assign unique CSS identifiers to each one. If you could just fix that for me, we'll be square. :D
delayedinsanity is offline  
Reply With Quote