【问题标题】:preg_match and preg_replace can't match patternpreg_match 和 preg_replace 不能匹配模式
【发布时间】:2015-08-18 01:22:21
【问题描述】:

我正在使用以下正则表达式模式来查找 url 的一部分:

$pattern = "(\d+)-.*";
//$pattern = "(\d+)-.*[.]htm.*";

$replacement = "/going/somewhere?$1";
$subject = "http://mudomain.com/59016-string.htm";
preg_match($pattern, $subject,$matches);
$final = preg_replace($pattern, $replacement, $subject);

echo $final;
var_dump($matches);

模式应该匹配

59016-string.htm

但我得到的只是 null 作为输出。 我在这里做错了什么?

已编辑: 得到解决方案后

供参考:

http://www.php.net/manual/en/regexp.reference.delimiters.php

http://php.net/manual/en/ref.pcre.php

【问题讨论】:

  • 使用正则分隔符:$pattern = '/(\d+)-.*/';
  • @stribizhev 该死的..我怎么错过了。你能写下你的评论作为答案吗?我会接受的。谢谢。

标签: php regex


【解决方案1】:

您忘记了正则表达式分隔符:

$pattern = '/(\d+)-.*/';

在 PHP 中,它们是不可或缺的。 另外,请注意我使用的是单撇号:这是故意这样做的,这样我们就不必将反斜杠加倍 \d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多