php 条件约定
我有一个系统,对某些数据使用关键字
有普通关键字和元关键字 - To:all、Tomember: 和 Togroup:
并且我有以下条件来检查元关键字:
if ((strpos($kwd, 'To:all') === 0) ||
(strpos($kwd, 'Tomember:') === 0) ||
(strpos($kwd, 'Togroup:') === 0))
{
/* ... */
}
我认为这种识别元关键字的方法是不正确的。
还有一种不正确的方法是这样的:
if ((strpos($kwd, 'To:all') !== FALSE) ||
(strpos($kwd, 'Tomember:') !== FALSE) ||
(strpos($kwd, 'Togroup:') !== FALSE))
{
/* ... */
}
在我看来,正确的方法是:
if ((substr($kwd,0,6) == 'To:all') ||
(substr($kwd,0,9) == 'Tomember:') ||
(substr($kwd,0,8) == 'Togroup:'))
{
/* ... */
}
有什么想法吗?
I have system, that using keywords for some data
There are normal keywords and meta keywords - To:all, Tomember: and Togroup:
and I have following condition to check meta keywords:
if ((strpos($kwd, 'To:all') === 0) ||
(strpos($kwd, 'Tomember:') === 0) ||
(strpos($kwd, 'Togroup:') === 0))
{
/* ... */
}
I think this way of identifying meta keywords is incorrect.
One more incorrect way is like this:
if ((strpos($kwd, 'To:all') !== FALSE) ||
(strpos($kwd, 'Tomember:') !== FALSE) ||
(strpos($kwd, 'Togroup:') !== FALSE))
{
/* ... */
}
And in my opinion the correct way is:
if ((substr($kwd,0,6) == 'To:all') ||
(substr($kwd,0,9) == 'Tomember:') ||
(substr($kwd,0,8) == 'Togroup:'))
{
/* ... */
}
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您提出的解决方案中,第二个是错误的,因为即使元关键字没有出现在
$kwd
的开头,它也会返回 true。另外两个工作正常。更好的方法是:
Of the solutions you propose, the second is wrong because it will return true even if the meta-keywords do not appear in the beginning of
$kwd
. The other two work correctly.An even better way would be:
将检查
$kwd
字符串开始是否以To:all
-- 它将检查To:all< 的位置
$kwd
中的 /code> 为 0。将检查
$kwd
字符串是否包含To:all
——无论在哪个位置。将检查
$kwd
的前 6 个字符是否为To:all
——这相当于第一个解决方案。如果您想测试开头为的情况,您将使用第一个或第三个解决方案。
就我个人而言,我会选择基于 strpos 的:我发现它更容易阅读/理解;但这主要是个人喜好问题。
如果您想测试 contains 情况,则需要使用第二种解决方案。
will check if the
$kwd
string begins withTo:all
-- it'll check if the position ofTo:all
in$kwd
is 0.will check if the
$kwd
string containsTo:all
-- no matter at which position.whill check if the first 6 characters of
$kwd
areTo:all
-- which is equivalent to the first solution.If you want to test the begins with case, you'll use the first or third solution.
Personnaly, I'd go with the strpos-based : I find it easier to read/understand ; but it's mainly a matter of personnal preferences.
If you want to test the contains case, you'll need to use the second solution.