PHP Learn It! PHP Replace String
Google

String Replace Using ereg_replace

String Replace

Learn PHP and MySQL fast!

Learn how you can start building rich interactive database driven sites like a professional developer easily and quickly...

>> Order your copy now for just $39.95 <<

Some time ago someone asked me over email how to replace double quoted substrings in a string with another substring. In another words, how to replace all occurrence of a substring in a string?

To explain more clearly, imagine you have a string as follow.

$str = 'this is a "test" string. Testing "this" string...';

Now imagine, we want to replace all substrings with-in double quotes with the string "sample". How would you do it?

Using preg_replace?

Using preg_replace and regular experssions will do the trick but preg_replace will only remove the first occruance of the string in double quotes. But we want to remove all occurrences of substrings in double quotes. How?

Using ereg_replace

To remove all occurrences, we need to use ereg_replace.

Lets jump right into the code and see how it is done.

string ereg_replace ( string $pattern, string $replacement, string $string )

ereg_replace replace takes three arguments.

Example 1: Using ereg_replace

<?php

$reg_ex = '"[A-Za-z]+"';
$replace_word = "sample"; 
$str = 'This is a "test" string. Testing "this" string...';

echo ereg_replace($reg_ex, $replace_word, $str);

?>

Output

This is a sample string. Testing sample string...

In the above example all substrings with in double quotes ("test" and "this") are replaced with string "sample".

Example 2: Using ereg_replace

Another example would be replacing all occurrences of " " (space) with – hyphen

<?php

$reg_ex = "[[:space:]]";
$replace_word = "_"; 
$str = "php string replace tutorial";

echo ereg_replace($reg_ex, $replace_word, $str);

?>

Output

php_string_replace_tutorial

This method will come very handy when manipulating strings in PHP.

Build large scalable dynamic websites using PHP yourself
Learn PHP like a pro >>

Top