Page 1 of 1

to replace a exact word

Posted: Mon Nov 30, 2009 4:46 am
by balamscint
hi all i need to replace a word in a string with exact match, in php

eg:

search string=center

replace string=center_another

subject=center centertop centerright centerleft

these all will be dynamic values

then result should be

subject=center_another centertop centerright centerleft

hers is my code

<?php
$s="center center_top centerleft center.right centerbottom center-width centerheight";

$t="center";

$find="/".$t."?/";

$find_r="center";

$replace=$find_r."_another";

preg_replace($find,$replace,$s);

?>


thanks in advance

Re: to replace a exact word

Posted: Mon Nov 30, 2009 10:05 am
by AbraCadaver
What's not working? Just a quick glance and it doesn't appear that you are assigning the returned string to anything.

Code: Select all

$result = preg_replace($find,$replace,$s);
echo $result;
-Shawn

Re: to replace a exact word

Posted: Mon Nov 30, 2009 10:08 am
by jackpf
Also, if you only want to match complete words, you can use a word-boundary - \b.

Re: to replace a exact word

Posted: Mon Nov 30, 2009 9:42 pm
by balamscint
hi,

sorry i forgot to include the echo.

the thing is it replaces all the occurence of word 'center' even 'centerbottom'.

am not familiar with the patterns. i need to replace only 'center' not other words with 'center' as part of the word

Re: to replace a exact word

Posted: Tue Dec 01, 2009 12:48 am
by balamscint
hi

thanks for you solutions.

i solved it by using the boundary option as you specified.

thanks again ...