Re: [PHP] str_replace on words with an array
- From: larry@xxxxxxxxxxxxxxxx (Larry Garfield)
- Date: Mon, 30 Oct 2006 19:49:23 -0500
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
.
- References:
- str_replace on words with an array
- From: "Dotan Cohen"
- Re: [PHP] str_replace on words with an array
- From: Stut
- Re: [PHP] str_replace on words with an array
- From: "Dotan Cohen"
- str_replace on words with an array
- Prev by Date: Re: [PHP] Re: A general UL script
- Next by Date: RE: [PHP] How do I get ini_set('output_handler', '') to work?!
- Previous by thread: Re: [PHP] str_replace on words with an array
- Next by thread: Re: [PHP] str_replace on words with an array
- Index(es):
Relevant Pages
|