Page 1 of 1

str_replace() reversed?

Posted: Thu Oct 09, 2003 10:41 am
by Gen-ik
Does anyone know how to strip a $var of everything except certain characters?

For example say I had "This is a big red ball with a big red stick" in a $string and wanted to remove everything apart from "big red" so that the $string would end up being "big red big red"...... probably not a great example but you catch my drift.

Any ideas?

Posted: Thu Oct 09, 2003 11:55 am
by SimonEast
I don't know of any function that does this - it sounds a little obscure. You'd probably have to write your own algorithm to handle this, maybe using strpos(), recording all the locations of particular phrases and then reconstructing a new string from the gathered data. Or maybe some regex wizardry would help.

< Simon >

Posted: Thu Oct 09, 2003 2:29 pm
by JAM
Think of this idea...

Make an array with allowed words.
Use explode() on your string using space as delim, and you get all words in a different array.
Loop each word in the second array using [url=http://se.php.net/manual/en/function.in-array.php]in_array() to see if it exists. If it does, keep it, else remove it using array_slice() or unset().
Left you have a string containing allowed words.

Posted: Thu Oct 09, 2003 3:43 pm
by Gen-ik
Thanks JAM. Your idea does the job fine :)

Posted: Thu Oct 09, 2003 7:34 pm
by SimonEast
Yeah, that's a good suggestion, however I thought you needed to look for phrases rather than individual words. Oh well, if that helps you out, then all good - problem solved.

< Simon >

thanks

Posted: Fri Oct 10, 2003 1:37 am
by itsmani1
Hay JAM !

UR idea did the trick

thanks.


Abdul Mannan

Posted: Fri Oct 10, 2003 2:43 pm
by murph
Also you can use a regular expression. preg_match would work fine...