Jump to content

[SOLVED] str_replace function


LiamProductions

Recommended Posts

str_replace — Replace all occurrences of the search string with the replacement string

 

$string = "lets replace me";

str_replace("replace", "", $string);

 

str_replace(SearchTerm, ReplacementTerm, Subject)

 

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

 

 

Will produce "lets me"

 

What a fun little example  :D

Link to comment
Share on other sites

So whatever is in the replacement turn gets changed to what is in the replacement term? so because you put "" it took out replace so it says lets me, but if you put:

 

$string = "lets replace me";

str_replace("replace", "kiss", $string);

 

If you put that code, would it say "Lets kiss me" ?

Link to comment
Share on other sites

A good example is if you are saving files and want to replace any of the spaces with underscores

 

<?php

$str = "hello world.gif";

$new_str = str_replace(" ","_",$str);

echo $str; // should give hello world.gif
echo $new_str; // should give hello_world.gif

?>

Link to comment
Share on other sites

<?php

$template = "<html><head><TITLE>%TITLE%</title></head><body>Welcome to <b>%TITLE%</b> Your name is %USER_NAME% we welcome you %USER_NAME%</body></html>";

$replace_array = array("%TITLE%" => "My Homepage", "%USER_NAME%" => "Jack of All Trades");

foreach ($replace_array as $replace => $what) {
   $template = str_replace($replace,$what,$template);   
}


echo $template;


?>

 

Makes it so you can store templates in databases easy without having to worry about using eval and being exploited etc.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.