Welcome Guest, Not a member yet? Register   Sign In
str_replace
#1

[eluser]basty_dread[/eluser]
this is my code:

Code:
$string = "web designers web designing web design";
$replace = "web design";

$finalstring = str_replace($replace, "<a href='google.com'>".$replace."</a>",$string);

echo $finalstring;

output:
Code:
<a href='google.com'>web design</a>ers <a href='google.com'>web design</a>ing <a href='google.com'>web design</a>

why did it include web designers? what i would like to happen is only web design should be replaced..
Thanks for help.
#2

[eluser]Rob Gordijn[/eluser]
[quote author="basty_dread" date="1265205070"]why did it include web designers?[/quote]

because 'web design' is in 'web designers'.

you can include an extra space at the end of your replace string so it doesn't match designers.

[edit]
P.s. you can look into preg_replace() for more 'solid' replace options in a string.
#3

[eluser]basty_dread[/eluser]
oh.. i really dont know how to use preg_replace
#4

[eluser]Rob Gordijn[/eluser]
well, it's not that hard Smile

little example:

Code:
$string = "web designers web designing web design";
$replace = "web design";
$finalstring = preg_replace('/('.$replace.')$/', '<a >\\1</a>', $string);
echo $finalstring;

the code above just replace the $replace string, ending with $ wich stands for end of line/string, so only 'web designer' will be replaced.
#5

[eluser]basty_dread[/eluser]
so when we have:
i add space at the end of the string:
Code:
$string = "web designers web designing web design ";

i tried it.. and it didnt find.. maybe i need to add something?
#6

[eluser]Rob Gordijn[/eluser]
hm, forgot what I said about adding an extra space for $replace.
Because it will work, but not if the $replace is founded at the end of $string (wich has no space at the end)

Look up the manual and some beginner tutorials about regular expressions, you will be amazed by it powers.
Someday regex will take over the world. lol Tongue
#7

[eluser]basty_dread[/eluser]
do you think exact matching could be possible?
wooh.. having hard time ...huhu
#8

[eluser]basty_dread[/eluser]
no one knows how to make exact match? please help.. thank you
#9

[eluser]Rob Gordijn[/eluser]
Sure someone knows. Don't be impatient.
Try something yourself, education is great Smile

Code:
$string = "web design web designers web designing web design";
$finalstring = preg_replace('/(web design\b)/', '<a >\1</a>', $string);
echo $finalstring;




Theme © iAndrew 2016 - Forum software by © MyBB