PHP:在不是价格小数点或字符串最后一个字符的第一个句点处拆分字符串

标签 php regex string split format

我想按照标题中列出的参数拆分字符串。我已经尝试了一些不同的方法,包括使用 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/

相关文章:

php - 如何防止数据库中存在多个这样的条目?

string - Swift - 用空格替换字符串中的表情符号

python - 用于替换不在引号之间的特定单词的正则表达式

php - 使用 2 个按钮从一张表单发送 POST 数据

php - 让 MySQL 每个条目仅返回一行

javascript - 排除包含正则表达式字符串的 URL

java - 存储来自正则表达式的反向引用供以后使用

c++ - 如何从 C++ 中的字符串返回子字符串?

php - 如何使用 PHP 进行倒计时

Python - 如何删除子字符串中直到并包括关键字的所有字符