开发者

PHP if/switch concatenated by *

I was wondering if anybody knew if there was a way to concatenate a * (all) 开发者_StackOverflow社区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 (:


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

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


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

$match = "/hello/";

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜