to replace a exact word

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
balamscint
Forum Newbie
Posts: 3
Joined: Mon Nov 30, 2009 4:24 am

to replace a exact word

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: to replace a exact word

Post 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
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: to replace a exact word

Post by jackpf »

Also, if you only want to match complete words, you can use a word-boundary - \b.
balamscint
Forum Newbie
Posts: 3
Joined: Mon Nov 30, 2009 4:24 am

Re: to replace a exact word

Post 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
balamscint
Forum Newbie
Posts: 3
Joined: Mon Nov 30, 2009 4:24 am

Re: to replace a exact word

Post by balamscint »

hi

thanks for you solutions.

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

thanks again ...
Post Reply