communication
 databases
 directories
 file handling
 html and code
 image editing
 image listing
 sessions and co
 string handling
 information
 forms
 apple stuff
 image handling
 array handling
 lixlpixel
php - snippets
google search terms detected and highlighted.
remove highlighting | keep highlighting
make snippet in "string handling" - download "string replace" - open demo of "string replace"
 search
php - snippets

Valid CSS!

php webring logo
prev next
random list
join the Ring!

string handling - string replace was created/last modified on Sat 24 Apr 2004 12:08 PM

some useful functions to replace strings in strings
   
<?php
   
   
// Multiple string replace
   // expects an array with $string => $replacement
   
$old_string = 'file_example.txt<br>another_file.txt<br>phpexample.php<br>';
   
$replacements = array('_'=>' ','<br>'=>' ,','.txt'=>' (Text)','.php'=>' (PHP)');
   
$new_string = strtr($old_string,$replacements);
   echo
$new_string;
   
   echo
'<hr>';
   
   
// Number Padding, PHP
   // Doesn't have to be zeros or numberic but handy for making sure you keep leading zeros on
   // day and month values when receiving such values as POST or GET variables.
   
$no_a = 3;
   
$no_a = str_pad($no_a, 2, '0', STR_PAD_LEFT);
   echo
$no_a;
   
   echo
'<hr>';
   
   
// String replacing, PHP
   
$old_string = 'the qick brown fox jumped over the lazy dog.';
   
$new_string = str_replace('qick brown fox', 'slow black bear', $old_string);
   echo
$new_string;
   
   echo
'<hr>';
   
   
// Remove tags using preg_replace, PHP
   // This should remove anything and everything everything between
   // 'less than' and 'greater than' characters
   
$source_string = '<b>bold</b> <a href="blank.php">link</a>';
   
$replacement = '(tag removed)';
   
$replaced_string = preg_replace('[<.*?.>]', $replacement, $source_string);
   echo
$replaced_string;
  
   echo
'<hr>';
   
   
// preg_replace can be used with arrays as well
   
$string = "The quick brown fox jumped over the lazy dog.";
   
$patterns = array('/quick/','/brown/','/fox/');
   
$replacements = array('slow','black','bear');
   echo
preg_replace($patterns, $replacements, $string);
   
?>

learn more about some of the PHP functions used in this snippet: array, echo, file, for, function, link, preg_replace, str_pad, str_replace, strtr, var

view the GNU general license - view the GNU library license - search on PHPsnippets - see your code like this

 a lixlpixel.com site

PHParadise.com - PHP-classes.org - your site on safari