1

我有以下代码,我需要对其进行调整,以获得所需的echo

<?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,但我不知道该怎么做。

谢谢。

4

2 回答 2

2

如果您只想匹配,有什么特别的理由使用 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...

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

于 2012-05-03T17:41:52.980 回答
0

这是你要找的吗?

$pattern = '/([0-9a-zA-Z,]+\.)(\d+)(.*)$/';
于 2012-05-03T17:41:35.840 回答