如何将字符串分成两边并在PHP中自动删除数字零?

时间:2015-02-26 03:58:18

标签: php string csv

我从CSV格式构建导入功能并将值插入数据库但是当我想更改代码格式时,我遇到了一些问题。

我有一些发票代码格式,如下面的代码,但我想分开其他代码格式

IP14010459
DEP14010460
IP14010461
DEP14010462
ISP14010462
ISP14010463
ISP14010464
ISP14010465
ISP14010466
ISP14010466
ISP14010467

我要将代码格式更改为

IP1401-459 (Zero has been deleted)
DEP1401-460 (Zero has been deleted)
IP1401-461 (Zero has been deleted)
DEP1401-462 (Zero has been deleted)
ISP1401-462 (Zero has been deleted)
ISP1401-463 (Zero has been deleted)
ISP1401-464 (Zero has been deleted)
ISP1401-465 (Zero has been deleted)
ISP1401-466 (Zero has been deleted)
ISP1401-466 (Zero has been deleted)
ISP1401-467 (Zero has been deleted)

我还删除了代码格式右侧的前缀(如果有)的数字0 我怎么能做这个朋友。

3 个答案:

答案 0 :(得分:4)

这可以使用substr_replace()

来实现
$str = "IP14010461";  //DEP14010462

echo substr_replace($str, '-', -4, 1);

输出:

IP1401-461  //DEP1401-462

$str = "IP14010461";
// $str = "DEP14010462";
echo substr_replace($str, '-', -4, 1) . "  (Zero has been deleted)";

使用对批处理有用的文件时:

if (($handle = fopen("1.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);    
        for ($c=0; $c < $num; $c++) {            

echo substr_replace($data[$c], '-', -4, 1) . "  (Zero has been deleted)";

            echo "<br />";  
        }
    }
    fclose($handle);
}

输出:

IP1401-459 (Zero has been deleted)
DEP1401-460 (Zero has been deleted)
IP1401-461 (Zero has been deleted)
DEP1401-462 (Zero has been deleted)
ISP1401-462 (Zero has been deleted)
ISP1401-463 (Zero has been deleted)
ISP1401-464 (Zero has been deleted)
ISP1401-465 (Zero has been deleted)
ISP1401-466 (Zero has been deleted)
ISP1401-466 (Zero has been deleted)
ISP1401-467 (Zero has been deleted)

答案 1 :(得分:0)

如果您有一个名为1.csv的文件,其中包含您的信息:

IP14010459
DEP14010460
IP14010461
DEP14010462
ISP14010462
ISP14010463
ISP14010464
ISP14010465
ISP14010466
ISP14010466
ISP14010467

你可以这样做:

<?php

$strings = file('1.csv');

for($i = 0; $i < count($strings); $i++) {
echo substr(trim($strings[$i]), 0, -4) . '-' . substr(trim($strings[$i]), -3) . ' (Zero has been deleted)' . "<br/>\n";
}

?>

答案 2 :(得分:0)

使用preg_replace

echo preg_replace("/(\D+\d{4})0*([1-9]+\d*)/i","$1-$2\n", "ISP14010462"); 

ISP1401-462

这取所有字母和4位数,删除0并保留其他数字