PHP if/switch 由 * 连接

发布于 2024-11-07 06:12:19 字数 284 浏览 3 评论 0原文

我想知道是否有人知道是否有一种方法可以将 * (全部)连接到 if (或 switch)语句内的字符串。例如,如果您有一个名为 /hello/there 和 /hello/whats-up ... 的 URL,那么您是否可以有类似以下内容的内容:

if ($url="/hello/" . *) {
sayHello();
} else { sayGoodebye(); }

等等... 我认为这不是正确的语法,但如果有人知道我在说什么这将是一个很大的帮助。

谢谢 (:

I was wondering if anybody knew if there was a way to concatenate a * (all) to a string inside an if (or switch) statement. For example if you had a URL called /hello/there and /hello/whats-up ... is there anyway you could have something like the following:

if ($url="/hello/" . *) {
sayHello();
} else { sayGoodebye(); }

etc... I don't think that's the correct syntax, but if anybody knows what I'm talking about it would be a great help.

Thanks (:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最美的太阳 2024-11-14 06:12:19
$match = "/hello/";
if (substr($url, 0, strlen($match)) === $match) {
   sayHello();
} else {
   sayGoodbye();
}

如果不需要,请不要使用正则表达式...

$match = "/hello/";
if (substr($url, 0, strlen($match)) === $match) {
   sayHello();
} else {
   sayGoodbye();
}

Do not use regular expressions if you don't have to...

妞丶爷亲个 2024-11-14 06:12:19

您还可以检查 $match 在 $url 字符串中的位置:

$match = "/hello/";

if (strpos($url, $match) === 0) {
   sayHello();
} else {
   sayGoodbye();
}

You can also check for the position of $match in the $url string:

$match = "/hello/";

if (strpos($url, $match) === 0) {
   sayHello();
} else {
   sayGoodbye();
}
苹果你个爱泡泡 2024-11-14 06:12:19

使用正则表达式:
http://www.regular-expressions.info/php.html

所以它是像这样的东西:

if (ereg("/hello/", $url)) {
sayHello();
} else { sayGoodebye(); }

虽然这会匹配任何地方带有“/hello/”的任何内容,所以如果您只想匹配以“/hello/”开头的字符串,则必须修改表达式。关键是,如果您从未使用过正则表达式,那么投入一些时间是一件好事。它最终会得到回报,因为在某些时候你会需要这项技能。

编辑:我将在这里留下原始代码作为参考,但请参阅 phihag 的注释并使用 preg_match 和 preg_match 兼容表达式而不是 ereg 和我使用的表达式。

Use regular expressions:
http://www.regular-expressions.info/php.html

So it would be something like this:

if (ereg("/hello/", $url)) {
sayHello();
} else { sayGoodebye(); }

Although that would match anything with "/hello/" in it anywhere, so if you only wanted to match strings that start with "/hello/" you'd have to modify the expression. The point is, if you've never used regular expressions it's a good thing to invest some time into. It'll pay off eventually because at some point you're going to need this skill.

Edit: I'll leave my original code here as reference, but please see phihag's comments and use preg_match and the preg_match compatible expression instead of ereg and the expression I used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文