PHP Regex使用preg_replace减少了空间

卡宁·佩恩维里亚库尔吉特

我有一些这样的字符串

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

我想转PCPrice ,这是导致我想要

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

起初我用

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

但这把我所有的PC都改为Price

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

这是我的代码。

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

但是结果是这样的

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

谢谢。

阿维纳什·拉吉(Avinash Raj)

正则表达式:

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

替换字符串:

$1 $2 Price $3

演示

$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);

输出:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

PHP preg_replace

来自分类Dev

如何使用preg_replace和regex表达式替换php文件中的代码块?

来自分类Dev

在PHP和regex中同时执行Preg_replace操作

来自分类Dev

PHP preg_replace RegEx删除空的段落标签

来自分类Dev

在PHP和regex中同时执行Preg_replace操作

来自分类Dev

php preg_replace用法-

来自分类Dev

PHP复杂preg_replace

来自分类Dev

PHP preg_replace HREF

来自分类Dev

PHP:preg_replace函数

来自分类Dev

PHP preg_replace HREF

来自分类Dev

PHP的条件preg_replace

来自分类Dev

使用php preg_replace替换最接近的匹配词

来自分类Dev

在PHP的preg_replace()中使用每个匹配项

来自分类Dev

与preg_replace一起使用的PHP substr

来自分类Dev

在PHP的preg_replace中使用反向引用

来自分类Dev

使用Preg_Replace PHP的条件运算符

来自分类Dev

如何在PHP中使用preg_replace()?

来自分类Dev

数组:使用 preg_replace 和排序过滤 [PHP - WordPress]

来自分类Dev

在 PHP 中使用 preg_replace - 奇怪的行为

来自分类Dev

PHP preg_replace 从 @ 到下一个空间

来自分类Dev

preg_replace vs trim PHP

来自分类Dev

php preg_replace()索引数组问题

来自分类Dev

PHP抓取和preg_replace

来自分类Dev

PHP preg_replace,拆分还是匹配?

来自分类Dev

PHP preg_replace URL模式

来自分类Dev

PHP preg_replace替换太多

来自分类Dev

PHP preg_replace多个URL替换

来自分类Dev

preg_replace vs trim PHP

来自分类Dev

PHP preg_replace与捕获组