/    Sign up×
Community /Pin to ProfileBookmark

replace exact string with another string

Hi,

i want to replace one string with another string in php. That replace should consider exact strting.

Ex: this is test

after replacing is with was i want my string to be “this was test”;

plz help me out for this.

Regards
Gopi.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiApr 27.2009 — [code=php]
$map = array(
'is' => 'was',
'foo' => 'bar',
'hello' => 'goodbye'
// etc
);
$string = 'hello! this is a string containing foo';
$string = str_replace(array_keys($map), $map, $string);
echo $string; // outputs "goodbye! this was a string containing bar"
[/code]
Copy linkTweet thisAlerts:
@gpbodapatiauthorApr 27.2009 — Thanks for your response Mindzai.

but it is replacing all the occurances. i don't want to replace all the occurances.

what exactly i want is,

$str = "this is test";

if i replace is with was, string should be "this was test"

i am using preg_match condition with word boundary

preg_match("/bisb/","was",$str)

it is returning "this was test";

if i use below string it is should not replace any word.

$str = "this -is test";

preg_match("/bisb/","was",$str)

but still it is replacing is with was like "this -was test";

my requirement is it should not replace any word.

This what exactly i need , Plz hep me
Copy linkTweet thisAlerts:
@NogDogApr 27.2009 — "-" is one of the things that will match for a word boundary ("b"). You could try some look-behind/-ahead assertions:
[code=php]
$new = preg_replace('#(?<=^|s)is(?=$|s)#', 'was', $str);
[/code]
×

Success!

Help @gpbodapati 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 6.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: @nearjob,
tipped: article
amount: 1000 SATS,

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

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...