preg_replace 个带数字的空格
preg_replace spaces with numbers
如何 preg_replace 我的文本中的所有空格都带有不同的后续数字?
作为
{"id":" "},{"id":" "},{"id":" "},
成为
{"id":"1"},{"id":"2"},{"id":"3"},
使用preg_replace_callback
函数的解决方案:
$text = '{"id":" "},{"id":" "},{"id":" "},';
$count = 0;
$text = preg_replace_callback('/" "(?=})/', function ($m) use(&$count){
return ++$count;
}, $text);
print_r($text);
输出:
{"id":1},{"id":2},{"id":3},
如果确实需要用双引号将数字括起来,请将回调的 return 表达式替换为以下内容:
return '"' . ++$count . '"';
如何 preg_replace 我的文本中的所有空格都带有不同的后续数字?
作为
{"id":" "},{"id":" "},{"id":" "},
成为
{"id":"1"},{"id":"2"},{"id":"3"},
使用preg_replace_callback
函数的解决方案:
$text = '{"id":" "},{"id":" "},{"id":" "},';
$count = 0;
$text = preg_replace_callback('/" "(?=})/', function ($m) use(&$count){
return ++$count;
}, $text);
print_r($text);
输出:
{"id":1},{"id":2},{"id":3},
如果确实需要用双引号将数字括起来,请将回调的 return 表达式替换为以下内容:
return '"' . ++$count . '"';