开发者

Trouble using indexed arrays with preg_replace() PHP

开发者 https://www.devze.com 2023-01-12 19:38 出处:网络
First time i post here an开发者_如何学God 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 th

First time i post here an开发者_如何学God 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 :)


This won't do?

implode(" ", range(0, 410))

It seems odd that you want to change them "in place".


Your "patterns" array looks like this:

$patterns (
   610 => '/$i/',
   611 => '/$i/',
...
}

You need to use double quotes on line 7:

$patterns[$i] = "/$i/";


Don't bother with regular expressions for such a simple case... Simply use str_replace. It'll be faster, and equivalent to your present code...

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

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

$string = str_replace($patterns, $replacements, $string);

Now, you'd still need to use preg_replace if the patterns are more complicated (such as only searching for the start of the line, etc)... But for such a simple pattern, it's not worth it (IMHO)...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号