如何使用strstr精确地匹配变量的内容而不仅仅是包含?
例如:
www.example.com/greenappleswww.example.com/redappleswww.example.com/greenapplesandpears如果我的URL被设置为变量$myurl,并且我使用以下..
if (strstr($myurl, 'redapples')) {
echo 'This is red apples';
}然后,它也适用于其他URL,因为它们还包括苹果这个词。我怎么能说得很具体?
发布于 2013-04-12 22:23:35
嗯,只是比较一下?
if ('www.mydomain.com/greenapples' === $myurl) {
echo 'green apples!';
}更新
没有进一步的信息,我不确定这是否符合您的问题,但如果您只对URL的最后一部分感兴趣,并考虑到URL包含查询字符串(例如?foo=bar&bar=foo)的可能性,请尝试如下所示:
// NOTE: $myurl should be INCLUDING 'http://'
$urlPath = parse_url($myurl, PHP_URL_PATH);
// split the elements of the URL
$parts = explode('/', $urlPath);
// get the last 'element' of the path
$lastPart = end($parts);
switch($lastPart) {
case 'greenapples':
echo 'green!';
break;
case 'greenapplesandpears':
echo 'green apples AND pears!';
break;
default:
echo 'Unknown fruit family discovered!';
}文档:
http://www.php.net/manual/en/function.parse-url.php
http://php.net/manual/en/function.end.php
http://php.net/manual/en/control-structures.switch.php
发布于 2013-04-12 22:44:07
我不知道PHP,但是这应该可以通过使用一些字符串操作来完成。使用substr(“www.mydomain.com/绿苹果”、strripos("www.mydomain.com/greenapples“、”/“);
strripos -返回子字符串的最后位置,在您的情况下说它的"/“。substr -在给定位置后返回子字符串。
像这样的你可以试试。
https://stackoverflow.com/questions/15981774
复制相似问题