我想根据标题中列出的参数拆分一个字符串.我try 了一些不同的方法,包括使用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})?skips(*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})?|[^.])+)-货币模式的一个或多个实例,或除.字符以外的任何一个字符
  • \.-.个字符
  • 第二组:绳子的其余部分.

Php相关问答推荐

Laravel 9如何过滤$的项目与结果?

Woocommerce自定义变体html表仅显示带值的列

在WooCommerce产品档案页面中显示产品销售百分比

MariaDB 11.3.2+PHP:服务器向客户端发送未知的字符集(0).请向开发人员报告

根据未用于变体的产品属性隐藏WooCommerce发货方式

WooCommerce我的帐户:从帖子作者处获取自定义帖子类型帖子ID

WooCommerce在购买后多次重定向

WooCommerce短代码,显示特定产品的购物车徽章中的当前数量

限制某些产品只能在WooCommerce的特定邮政编码/邮政编码范围内发货

带Redhat php curl的http_code 0

如何在WordPress REST API中判断应用程序密码

为什么WooCommerce的动作钩子';woocommerce_checkout_update_order_review';包含旧信息?

允许在WooCommerce管理订单列表中使用计费邮箱进行搜索

在 PHP 中将字符串分解为数组(字符串类似于 WP 短代码)

将自定义字段添加到管理产品 在 WooCommerce 3.2+ 中批量编辑

在具有Angular 的 Laravel 应用程序中,不显示图像

invalid_grant 和无效的 JWT 签名

如果 Select 的县不是store 所在的县,如何隐藏本地自提?

批量更新 WooCommerce 中所有产品的特定自定义字段

从 d-m-Y 日期格式 laravel 计算月份 = 01 的列的总和