<?php header('Content-type: text/plain'); ?>
If you have a FIXED string '{F3}'.. and it gets replaced with some other FIXED string say 'Foo'.. you should look at the function str_replace()
if you have a list of FIXED strings to translate into other FIXED string look into the string translate function, which does this with arrays in bulk :
strtr()
In your example, you would probably want to use the
preg_replace_callback() function... this would find a PATTERN and replace it with the value returned by some FUNCTION. callback=function
for your regular expression you would need for it to find the whole pattern, but remember only the number from it
this would find your string exactly, but it would remember it all, not just the number.
the bracket '{' is a special character to regular expression we we must { it
$pregex = '/{F3}/';
this would find your string exactly, and it would remember the number seperately,
in fact it will remember anything in () seperately
$pregex = '/{F(3)}/';
you might want any number, not just 3, so we ask for that with \d meaning any digit 0-9
$pregex = '/{F(\d)}/';
the number might be more than one digit long, so we add +, which means 1-infinity occuraces
$pregex = '/{F(\d+)}/';
for sanity reasons you may want to restrict this to numbers with say 1-10 digits.
we do this with a number range between brackets {1,10}
$pregex = '/{F(\d{1,10})}/';
wow its really starting to look messy isn't it. We are going to use preg_match_all for the moment so we can actually see what the regular expression is thinking before we add in the callback
$orig_string = '{F1} red {F22} socks {F333}';
$pregex = '/\\{F(\\d{1,10})\\}/';
$result = array();
$new_string = preg_match_all($pregex,$orig_string,$result);
print_r($result);
Array
(
[0] => Array
(
[0] => {F1}
[1] => {F22}
[2] => {F333}
)
[1] => Array
(
[0] => 1
[1] => 22
[2] => 333
)
)
so we can see our () are in fact capturing the correct portion, just the number
lets see what happens when the callback function gets called.
function foo($input)
{
print_r($input);
return 'foo()';
}
$orig_string = '{F1} red {F22} socks {F333}';
$pregex = '/\\{F(\\d{1,10})\\}/';
$new_string = preg_replace_callback($pregex,'foo',$orig_string);
echo $new_string;
Array
(
[0] => {F1}
[1] => 1
)
Array
(
[0] => {F22}
[1] => 22
)
Array
(
[0] => {F333}
[1] => 333
)
foo() red foo() socks foo()
so the callback actually gets passed two things, the entire captured portion, followed by each section of () we have.
function foo2($input)
{
$num = $input[1];
return "foo($num)";
}
$orig_string = '{F1} red {F22} socks {F333}';
$pregex = '/\\{F(\\d{1,10})\\}/';
$new_string = preg_replace_callback($pregex,'foo2',$orig_string);
echo $new_string;
foo(1) red foo(22) socks foo(333)
and viola... this should do it for you1