str_replace() reversed?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

str_replace() reversed?

Post 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?
SimonEast
Forum Newbie
Posts: 5
Joined: Thu Oct 09, 2003 11:00 am
Location: Melbourne, AUS

Post 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 >
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

Thanks JAM. Your idea does the job fine :)
SimonEast
Forum Newbie
Posts: 5
Joined: Thu Oct 09, 2003 11:00 am
Location: Melbourne, AUS

Post 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 >
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

thanks

Post by itsmani1 »

Hay JAM !

UR idea did the trick

thanks.


Abdul Mannan
murph
Forum Commoner
Posts: 29
Joined: Fri Oct 03, 2003 1:28 pm
Location: washington

Post by murph »

Also you can use a regular expression. preg_match would work fine...
Post Reply