【问题标题】:WordPress regex not working as expectedWordPress 正则表达式无法按预期工作
【发布时间】:2016-11-18 15:58:36
【问题描述】:

我需要将user-profile/id=3 之类的字符串放入正则表达式形式。我试过'user-profile/id=\d+$''user-profile/([a-z][.][0-9]+)/?$',但它们都没有工作。正确的方法是什么?

【问题讨论】:

  • 你想用正则表达式从这个字符串中得到什么?
  • 我只想提取id=3部分。
  • 那我希望我的回答能帮到你。
  • 您真的不想要一个简单的explode("/", $s)[1] 方法吗?我的印象是您的字符串始终采用上述格式,您不需要正则表达式。见ideone.com/2QFYks
  • 我为您添加了 2 个非正则表达式解决方案。我希望它们会有用。

标签: php regex wordpress


【解决方案1】:

由于您的字符串始终采用上述格式,因此您不需要正则表达式。仅使用explode

explode("/", $s)[1]

this demo

另一种非正则表达式方法:使用strstr 获取/ 之后并包括/ 的子字符串,然后从1 字符中获取substring:

substr(strstr($s, "/"),1);

another PHP demo

【讨论】:

    【解决方案2】:

    您的问题是您没有使用反斜杠转义 / 字符。

    解决该问题后您可能会立即面临的另一个问题是您正在使用$ 字符,这意味着行尾。如果后面有更多的字符,即使只是一个空格,也不会匹配。

    如果你尝试:

    user-profile\/(id=\d+)
    

    您可能会发现它匹配得很好。我添加的括号将在捕获组#1 中捕获id=3

    【讨论】:

    • 没有必要在正则表达式中转义/。试试'~user-profile/(id=\d+)~'
    【解决方案3】:

    如果你只是想提取id=3,我推荐使用preg_replace。喜欢:

    $str = 'user-profile/id=3';
    $after_preg = preg_replace('/user-profile\//', '', $str);
    echo $after_preg;
    

    如果你只想得到一个数字,可以如下:

    $str = 'user-profile/id=3';
    $after_preg = preg_replace('/user-profile\/id=/', '', $str);
    echo $after_preg;
    

    更多相关信息您可以阅读PHP Manual: preg_replace

    如果你想检查你的字符串是否像user-profile/id=3,你可以使用正则表达式:

    user-profile\/id=\d*
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多