PHP Scripts – WordPress Tutorials

You can find and replace a string in php easily using str_replace() function. I will go with example to make it easy for you. For example I have some string and I want to replace all the vowels from that string, it would be easy to use str_replace() here.

I have number of contents and I want to replace all the commas (“) there, I would use str_replace().

Let’s have a look at the syntax of str_replace(), take care of the parameters, use as I have used.

Str_replace(Search_for,Replace_with,Apply_to);

I am putting some code examples here to make it better understandable for you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$originalString    =    "Hello my name is mudasir nazir and i am testing Str_replace()";
echo 'Orignal String = '.$originalString;
$vowels    =    array("a","e","i","o","u");

$newString    =    str_replace($vowels,"",$originalString);
echo '<br />This is New String = '.$newString.'<hr/>';
//This will output Hll my nm s mdsr nzr nd m tstng Str_rplc()

$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.

$letters = array('e', 'p');
$fruit   = array('apple', 'pomogranate');
$text    = 'e p';
$output  = str_replace($letters, $fruit, $text);
echo '<br />'.$output;

// Output is apomogranatepomogranatele pomogranate

Don’t Forget to comment or email if you have some more to say. Send me more examples then I will update the post.

Random Posts


Categories: PHP