修改$pattern以获得所需的结果与preg_replace


Modify $pattern to get the desired result with preg_replace

我有以下代码,我需要调整它以获得所需的回声

<?php
$price = "A1,500.99B";
$pattern = '/(['d,]+'.)('d+)(.*)$/';   // This is something that I need to change, in order to get the desired result
$formatted_1 = preg_replace($pattern, '$1', $price);
$formatted_2 = preg_replace($pattern, '$2', $price);
$formatted_3 = preg_replace($pattern, '$3', $price);
$formatted_4 = preg_replace($pattern, '$4', $price);
echo $formatted_1;   // Should give A
echo $formatted_2;   // Should give 1,500
echo $formatted_3;   // Should give 99
echo $formatted_4;   // Should give B
?>

我知道我应该在$pattern内添加另一个带有内部内容的 ( ),并调整上述$pattern,但我不知道该怎么办。

谢谢。

如果您只是想要匹配,有什么特别的理由使用preg_replace吗?

此模式将与您的价格相匹配:

/([a-zA-Z])(['d,]+)'.('d+)([a-zA-Z])/

如果你随后编写这个 PHP:

$price = "A1,500.99B";
//Match any letter followed by at least one decimal digit or comma 
//followed by a dot followed by a number of digits followed by a letter
$pattern = '/([a-zA-Z])(['d,]+)'.('d+)([a-zA-Z])/';
preg_match($pattern,$price,$match);
$formatted_1 = $match[1];
//etc...

您将拥有四场比赛。 显然,您需要添加自己的异常处理。

这是你要找的吗?

$pattern = '/([0-9a-zA-Z,]+'.)('d+)(.*)$/';