【问题标题】:Regex in PHP winth preg_matchPHP中的正则表达式与preg_match
【发布时间】:2021-09-01 10:53:36
【问题描述】:

我在 PHP 中使用 preg_match 和 REGEX 来更改包含以下内容的字符串的路径变量:

“任何字符 - 油漆,1 到 14 之间的旧数字 - 任何字符”

我放了有效字符串的例子:

-油漆,老 12

-油漆,旧 0a

-油漆,旧 6b

...

我使用 preg_match 如下:

if(preg_match("/*paint, old ^([1-9]|1[0-4])*/",$ubicacion))
{
    ...
}
else
{
    ...
}

但它给了我这个错误:preg_match (): Compilation failed: nothing to repeat at offset 0

你知道什么是失败的吗?

【问题讨论】:

标签: php regex preg-match


【解决方案1】:

preg_match (): Compilation failed: nothing to repeat at offset 0 在大多数情况下是由于正则表达式开头存在量词。 正则表达式不能以量词开头,即/+1//*1//{2,}1//{2,5}1/ 会抛出此错误。

你可以使用

if (preg_match('~\bpaint,\s+old\s+(1[0-4]|[1-9])(?!\d)~i', $string)) {
...
}

请参阅 regex demothis PHP demo详情

  • \b - 单词边界
  • paint, - paint, 字符串
  • \s+ - 一个或多个空格 -old - old 字符串
  • \s+ - 一个或多个空格
  • (1[0-4]|[1-9]) - 1 后跟一个从 04 的数字或非零数字
  • (?!\d) - 后面没有任何其他数字。

请注意,您不需要在开头和结尾添加任何模式来实际使用预期匹配前后的文本,因为您只需要一个布尔结果。

末尾的i 使模式匹配不区分大小写。

【讨论】:

  • 谢谢,编译器错误已经消失,但效果不佳...不要更改变量,在某些情况下应该更改它...在“paint, old”前面可以是很多词,例如:“Basement, Left Warehouse, Paint, Old 14a”
  • @wiki 我添加了"fake" PHP demo,只要确保将正确的代码插入正确的代码块即可。匹配之前的内容无关紧要,preg_match 会在字符串中的任何位置找到匹配项。
  • 谢谢,但字符串的值可以是,例如:“Basement, Left Warehouse, Paint, Old 14a”。有了这个 valor ,它表明:“没有匹配!”我期望:“有一场比赛”。我想在一个很长的字符串中找到模式:paint, old (number between 1 and 14)
  • @wiki 添加/i 标志,if (preg_match('~\bpaint,\s+old\s+(1[0-4]|[1-9])(?!\d)~i', $string)) {
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
相关资源
最近更新 更多