尽管在正则表达式测试器中看起来工作正常,但 PHP 正则表达式没有产生预期的结果


PHP regex not producing desired result despite appearing to work OK in regex tester

我有一个PHP搜索并替换正则表达式,这给我带来了一些麻烦。我已经在 http://www.regextester.com/index2.html 使用了正则表达式测试器来测试它作为 preg 并且它在那里工作,但我似乎无法在我正在处理的 PHP 脚本中获得所需的结果。

下面是正则表达式的代码:

$result = preg_replace('/^prescriptions-a-z'/prescriptions-([a-z]{1}-[a-z]{1})'/([-a-z0-9_]*)'.html$/', '$1 $2', $url);

$url中的字符串是

prescriptions-a-z/prescriptions-a-c/atopica-capsules.html

结果应该是

a-c atopica-capsules

但是,它返回一个空结果。谁能说明为什么这不能产生我想要的输出?

回去查看代码后,我已经弄清楚了它是什么 - 事实证明早期的正则表达式是错误的,因此代码首先没有执行。哎呀!不过,它现在工作正常。谢谢你们的帮助!

<?php
$url = 'prescriptions-a-z/prescriptions-a-c/atopica-capsules.html';
$result = preg_replace('/^prescriptions-a-z'/prescriptions-([a-z]{1}-[a-z]{1})'/([-a-z0-9_]*)'.html$/', '''1 ''2', $url);
echo $result;

参考文献使用''字符而不是$,可以查看函数手册

您的替换不正确

'$1 $2'应该'''1 ''2'