我想按照标题中列出的参数拆分字符串。我已经尝试了一些不同的方法,包括使用 preg_match,但到目前为止收效甚微,我觉得可能有一个更简单的解决方案,但我还没有注意到。
我有一个匹配标题中提到的“价格”的正则表达式(见下文)。
/(?=.)\£(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9] +)?(\.[0-9]{1,2})?/
下面是一些示例场景以及我想要的结果:
示例 1:
input: "This string should not split as the only periods that appear are here £19.99 and also at the end."
output: n/a
示例 2:
input: "This string should split right here. As the period is not part of a price or at the end of the string."
output: "This string should split right here"
示例 3:
input: "There is a price in this string £19.99, but it should only split at this point. As I want it to ignore periods in a price"
output: "There is a price in this string £19.99, but it should only split at this point"
最佳答案
我建议使用
preg_split('~\£(?:[1-9]\d{0,2}(?:,\d{3})*|[0-9]+)?(?:\.\d{1,2})?(*SKIP)(*F)|\.(?!\s*$)~u', $string)
参见 regex demo .
模式与您的模式匹配,\£(?:[1-9]\d{0,2}(?:,\d{3})*|[0-9]+)?(?:\.\d{1,2})?
并跳过 (*SKIP)(*F)
, 否则,它匹配一个非最终的 .
与 \.(?!\s*$)
(即使有尾随空白字符)。
如果您真的只需要在第一次出现符合条件的点时拆分,您可以使用匹配方法:
preg_match('~^((?:\£(?:[1-9]\d{0,2}(?:,\d{3})*|[0-9]+)?(?:\.\d{1,2})?|[^.])+)\.(.*)~su', $string, $match)
参见 regex demo .这里,
-
^
- 匹配字符串开始位置 -
((?:\£(?:[1-9]\d{0,2}(?:,\d{3})*|[0-9]+)?(?:\.\d{1,2})?|[^.])+)
- 一次或多次出现您的货币模式或除.
以外的任何一个字符字符 -
\.
- 一个.
字符 -
(.*)
- 第 2 组:字符串的其余部分。
关于PHP:在不是价格小数点或字符串最后一个字符的第一个句点处拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71425320/