Using replace functions in PHP
It is important that PHP programmers should know well about functions available to manipulate text strings in PHP. PHP has many powerful functions for string manipulation which are handy when working with database or file handling projects.
PHP offers few string replace functions and in this article we can have a look at some of these functions.
If we need to replace a simple string, we can use str_replace() or str_ireplace().
str_replace()
This will replace given string within a string. This may be case sensitive
Example,
| Code: |
| <?php
echo str_replace("oldword", "newword", "This should be my string and has oldword in it."); ?> |
str_ireplace()
This is case-insensitive version of str_replace().
Example,
| Code: |
| <?php
echo str_ireplace("oldword", "newword", "This should be my string and has oldword in it."); ?> |
If you would like to replace the strings using some complicated strings, you can use ereg_replace() or preg_replace()
ereg_replace()
Using this function you can pass a pattern and replace the string within the string.
Example,
Removing unwanted character from a string.
| Code: |
| <?
echo ereg_replace("[^[:alnum:]+]","","somebad)file$nam&me;!"); ?> |
ereg_ireplace()
This is case-insensitive version of ereg_replace().
Removing extra spacing from a string
<?
$sTest = "This is a test. but ";
echo eregi_replace(" +", " ", $sTest);
?>
preg_replace()
This is again a regular expression function to replace the strings.
Example,
Replace all the URLs in a string to proper hyper links.
| Code: |
| <?
echo preg_replace("/(http:\/\/|ftp:\/\/)([^\s,]*)/i","<a href='$1$2'>$1$2</a>","test url http://www.google.com"); ?> |
Hope this short article will help you. Please post your comments and suggestions here.
I will try to add more examples in the comment section.
Happy programming!
Commentaires
Enregistrer un commentaire