Re: str_replace on words with an array

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

 



On 31/10/06, Larry Garfield <larry@xxxxxxxxxxxxxxxx> wrote:
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?

I think that was my mistake- not differentiating between the two.
Symbols and such I wanted to replace as substrings, yet noise words I
wanted to replace as words. Now that I've created two arrays, one with
symbols and one with noise words, things are on track.

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";

I was completely unaware of the array_map function. Thank you- that is
exactly what I needed.

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.

Yep.

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.

Yep.

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

It certainly does. Of course I'm not using it exactly how you pasted
it, but you got me on track. Thank you very much.

To all others who took part in this thread: I was unclear on another
point as well, the issue of sql-injection. As I'm removing the
symbols, signs, and other non-alpha characters from the query, I
expect it to be sql-injection proof. As I wrong? ie, could an attacker
successful inject sql if he has nothing but alpha characters at his
disposal? I think not, but I'd like to hear it from someone with more
experience than i.

Thank you.

Dotan Cohen

http://what-is-what.com

--
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