...

View Full Version : Trouble using indexed arrays along with preg_match



PhPNovice
08-19-2010, 03:27 PM
Hi there. First time i post here and hope somebody will be able to help me.

I have a file whos numbering starts at 610 and goes on to 1019. I want to use PHP's preg_match() function to start the numbering from 0 and go on till 410.

Here is some code i've been working on. But i cant get the function to replace the numbers. I don't know why and i don't get any errors.

<?php

$string = "610 611 612 613 614 615 616 617"; //this isnt the actual file but will do. The actual file is more complicated. This is just a test string.

$patterns = array();
for ($i=610; $i<1020; $i++) {
$patterns[$i] = '/$i/';
}

$replacements = array();
for ($j=1; $j<410; $j++) {
$replacements[$j] = '\r\n' . $j;
}

$newText = preg_replace($patterns, $replacements, $string);
echo $newText;

?>

I used Example #2 form http://www.php.net/manual/en/function.preg-replace.php as reference.

Thanks in advance for any help :)

disastro
08-19-2010, 04:03 PM
You are actually very close.

This should work:


<?php

$string = "610 611 612 613 614 615 616 617"; //this isnt the actual file but will do. The actual file is more complicated. This is just a test string.

$patterns = array();
for ($i=610; $i<1020; $i++) {
$patterns[$i] = "/$i/";
}

$replacements = array();
for ($j=1; $j<410; $j++) {
$replacements[$j] = "\r\n" . $j;
}

$newText = preg_replace($patterns, $replacements, $string);
echo $newText;

?>

Notice how $patterns[$i] is quoted. With single quotes, PHP assigns the literal value ('/$i/' = /$i/). With double quotes, PHP will expand $i.

You can read more on how PHP parses variables in strings here:
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

PradeepKr
08-20-2010, 01:09 PM
some beautification,

$patterns = array();
foreach (range(610, 1019) as $number) {
$patterns[] = $number;
}


Similarly for the other array.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum