Re: str_replace on words with an array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Monday 30 October 2006 15:10, Dotan Cohen wrote:

> Er, so how would it be done? I've been trying for two days now with no
> success.

>From your original message, it sounds like you want to strip selected complete 
words, not substrings, from a string for indexing or searching or such.  
Right?

Try something like this:

$string = "The quick sly fox jumped over a fence and ran away";
$words = array('the', 'a', 'and');

function make_regex($str) {
  return '/\b' . $str . '\b/i';
}

$search = array_map('make_regex', $words);
$string = preg_replace($search, '', $string);
print $string . "\n";

What you really need to do that is to match word boundaries, NOT string 
boundaries.  So you take your list of words and mutate *each one* (that's 
what the array_map() is about) into a regex pattern that finds that word, 
case-insensitively.  Then you use preg_replace() to replace all matches of 
any of those patterns with an empty string.  

You were close.  What you were missing was the array_map(), because you needed 
to concatenate stuff to each element of the array rather than trying to 
concatenate a string to an array, which as others have said will absolutely 
not work.

I can't guarantee that the above code is the best performant method, but it 
works. :-)

-- 
Larry Garfield			AIM: LOLG42
larry@xxxxxxxxxxxxxxxx		ICQ: 6817012

"If nature has made any one thing less susceptible than all others of 
exclusive property, it is the action of the thinking power called an idea, 
which an individual may exclusively possess as long as he keeps it to 
himself; but the moment it is divulged, it forces itself into the possession 
of every one, and the receiver cannot dispossess himself of it."  -- Thomas 
Jefferson

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux