String Replace Using ereg_replace
|Click on a Topic [ Hide ]|
|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 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?
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.
- pattern - the regular expression for matching substring
- replacement - the replacement substring
- string - the actual string
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); ?>
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); ?>
This method will come very handy when manipulating strings in PHP.
Are you still stuck using HTML?
"Learn how to build websites using PHP and MYSQL"