dpict99695329 2014-09-27 11:42 采纳率: 100%
浏览 29
已采纳

PHP Regex使用preg_replace切断空间

I have some string like this

Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300

I want to turn PC to Price And this is result that I want

Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300

At first I use

$pattern = array('/(\s*)Product(\s*)/', '/(\s*)(Pc\.?|Pcs)(\s*)/');

But it came to change all of my PC to Price

Name xxx Product 1 Price 100
Name Price i Product 2 Price 200
Name Price x Product 3 Price 300

This is my code now.

$pattern = array('/(\s*)Product(\s*)/', '/[^a-z](Pc\.?|Pcs)[^a-z]/');
$replacement = array(' Product ', ' Price ');
$title = preg_replace($pattern, $replacement, $title, -1);

But it result like this

Name xxx Product 1 Price 100
Name Pci Product Price 00
Name Pcx Product 3 Price 00

Thanks you.

  • 写回答

2条回答 默认 最新

  • dongpan1365 2014-09-27 11:48
    关注

    Regex:

    (Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)
    

    Replacement string:

    $1 $2 Price $3
    

    DEMO

    $string = <<<EOT
    Name xxx Product 1 Pc 100
    Name Pci Product2Pc.200
    Name Pcx Product 3 Pcs300
    EOT;
    $pattern = "~(Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)~";
    echo preg_replace($pattern, "$1 $2 Price $3", $string);
    

    Output:

    Name xxx Product 1 Price 100
    Name Pci Product 2 Price 200
    Name Pcx Product 3 Price 300
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line