/    Sign up×
Community /Pin to ProfileBookmark

str_replace full words only

I have a word list I am using to remove common words from a user’s input. I’m using str_replace with an array of the words but this is causing some problems. Able is a word in the list so this removes able from any word, such as available. Is there a single line solution to this without doing an if… then?

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@so_is_thisOct 25.2006 — Yes, just use the syntax to operate on a word boundary.

EDIT: I went and looked it up. It is the b selector.
Copy linkTweet thisAlerts:
@ephmynusauthorOct 25.2006 — Thanks. Where is the list of all of these options?
Copy linkTweet thisAlerts:
@so_is_thisOct 25.2006 — Various places -- but I find it easier to go here:

[URL=http://msdn.microsoft.com/library/en-us/script56/html/ab0766e1-7037-45ed-aa23-706f58358c0e.asp]MSDN Regular Expression Syntax[/URL]

I guess a PHP-specific reference would be better:

[url=http://us2.php.net/manual/en/reference.pcre.pattern.syntax.php]PHP Regular Expression Syntax[/url]
Copy linkTweet thisAlerts:
@bokehOct 25.2006 — b is a zero width assertion that works as part of a regex. Str_replace is not a regex function. You could either switch to a regex function (preg_replace) or continue to use str_replace but put a space before and after the word in your search array and replace it with a space. Example: [code=php]$done = str_replace(' able ', ' ', $target);[/code]
Copy linkTweet thisAlerts:
@so_is_thisOct 25.2006 — Whoops! I overlooked the fact that [B]str_replace()[/B] was involved here. Sorry.

Yes, to use b you would have to switch to the [B]preg_replace()[/B] function.
×

Success!

Help @ephmynus spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...