number replace

A

Anonymous

Guest
How can I search for a number in a string and replace it with another value?

I.E

string: This is a string with the number 133

and I want to replace it with the number * 700.

Ive got this code:

Code:
<?php


$slots = explode("\r\n", trim($_POST['slots']));
foreach ($slots as $n=>$slot)
{
//here will the replace code be
}

?>

And if you could explain what the code do ( if you past any ) I would be grateful.
 
Following code would help you in sorting out your problem.

Code:
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

Output
The bear black slow jumped over the lazy dog.
 
If you want to replace the number 133 with 700 you could also use:

Code:
<?php
$str = str_replace("133", "700", $str);
?>
 
Back
Top