连接正则表达式

Concatenate regex

我正在尝试将所有这些都整合到一个查询中,但我的正则表达式技能并不高超。我确实让它以这种不优雅的方式工作。非常感谢任何帮助。

来源 $url 看起来像这样:

/o/33484/bob-nonami

我需要的最终结果如下所示:

bob-nonami

这是可以提高效率的地方

$urlName1 = preg_replace("/[0-9]/","",$url);
$urlName2 = preg_replace("/(o)/","",$urlName1);
$urlName = preg_replace("/(\/)/","",$urlName2);

只需将其他字符包含在您的 character class 中以进行替换。

$url = "/o/33484/bob-nomai";
echo preg_replace("~^/o[0-9/]+~", "", $url); // bob-nomai

你不可能这样做 preg_replace("/(o)/", "", $urlName1) 因为那样只会得到字符串 "bb-nmai",这显然不是你想要的。

相反,您似乎想删除字符串开头的前导 "/o",这可以在 PCRE with an anchor.

中实现

Outside a character class, in the default matching mode, the circumflex character (^) is an assertion which is true only if the current matching point is at the start of the subject string.

因此 ^/o 将匹配主题开头的 /o[0-9/].

的任何后续字符