PHP Noob
PHP Noob

Reputation: 1615

filter words on a string in PHP

I have a string in which all of the beginning of every word are capitalized. Now i want to filter it like if it can detect words link "as, the, of, in, etc" it will be converted to lower cases. I have a code that replace and convert it to lower case, but for 1 word only like below:

$str = "This Is A Sample String Of Hello World";
$str = preg_replace('/\bOf\b/', 'of', $str);

output: This Is A Sample String of Hello World

So what i want is that to filter other words such as on the string like "is, a". Its odd to repeat the preg_replace for every word to filter.

Thanks!

Upvotes: 2

Views: 3917

Answers (4)

eaglethedev
eaglethedev

Reputation: 1

$replace = array(
'dog' => 'cat',
'apple' => 'orange',
'chevy' => 'ford'
 );

$string = 'I like to eat an apple with my dog in my chevy';
function strReplaceAssoc(array $replace, $subject) {
    return str_replace(array_keys($replace), array_values($replace),     $subject);   
}
echo strReplaceAssoc($replace,$string);

Upvotes: 0

flowfree
flowfree

Reputation: 16462

Try this:

$words = array('Of', 'Is', 'A', 'The');  // Add more words here

echo preg_replace_callback('/\b('.implode('|', $words).')\b/', function($m) {
    return strtolower($m[0]);
}, $str);


// This is a Sample String of Hello World

Upvotes: 1

Jeroen
Jeroen

Reputation: 13257

Use preg_replace_callback():

$str = "This Is A Sample String Of Hello World";
$str = ucfirst(preg_replace_callback(
       '/\b(Of|Is|A)\b/',
       create_function(
           '$matches',
           'return strtolower($matches[0]);'
       ),
       $str
   ));
echo $str;

Displays "This is a Sample String of Hello World".

Upvotes: 3

Isaac Hildebrandt
Isaac Hildebrandt

Reputation: 1026

Since you know the exact word and format you should be using str_replace rather than preg_replace; it's much faster.

$text = str_replace(array('Is','Of','A'),array('is','of','a'),$text);

Upvotes: 3

Related Questions