在preg_replace()PHP中使用索引数组时遇到问题

在preg_replace()PHP中使用索引数组时遇到问题,php,arrays,preg-match,Php,Arrays,Preg Match,我第一次在这里发帖,希望有人能帮助我 我有一个文件的编号从610开始一直到1019。我想使用PHP的preg_match()函数从0开始编号,一直到410 这是我一直在编写的一些代码。但是我不能得到替换数字的函数。我不知道为什么,也没有任何错误 <?php $string = "610 611 612 613 614 615 616 617"; //this isnt the actual file but will do. The actual file is more complic

我第一次在这里发帖,希望有人能帮助我

我有一个文件的编号从610开始一直到1019。我想使用PHP的preg_match()函数从0开始编号,一直到410

这是我一直在编写的一些代码。但是我不能得到替换数字的函数。我不知道为什么,也没有任何错误

<?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;

?>

我使用示例2表单作为参考

提前感谢您的帮助:)

这样不行吗

implode(" ", range(0, 410))
你想“就地”改变它们,这似乎很奇怪

您的“模式”数组如下所示:

$patterns (
   610 => '/$i/',
   611 => '/$i/',
...
}
您需要在第7行使用双引号:

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

对于这样一个简单的情况,不要费心使用正则表达式。。。只需使用str_替换即可。它会更快,相当于您当前的代码

$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);
$patterns=array();

对于($i=610;$i你能描述一下什么对你不起作用吗?输入、输出和预期的输出都会有帮助…不要在
'/$i/'
'\r\n'
上使用单引号。改为使用双引号。这里的区别是:我不知道,但我觉得在这种情况下使用正则表达式很奇怪。@Bolt这并不是那么奇怪。这是个诡计y使用
str_replace()正是我所想的。你错过了这条评论:
//这不是实际的文件,但可以。实际的文件更复杂。这只是一个测试字符串。
@Null不,我读过。但它没有提供任何洞察。如果有任何问题,它可能会使正则表达式解决方案不那么理想,因为如果后面有文本,它可能包含一些numbers.
'\r\n'
不会是新行。
str\u replace()
也不适用于此(考虑单词边界)我知道。但他说他在处理文件。所以我假设他知道这不会是一个新行,并想在其中添加一个文字
\r\n
。。我不确定这是错误还是明确的,所以我只使用他提供的内容…是的,如果OP提供实际的输入和预期的输出文件会有所帮助