在逗号分隔的前缀列表中查找前缀的有效方法
I have a prefix stored in a variable
$prefix = “07”;
And coma separated list of prefixes stored in another variable (the list is provide by user using text box)
$allPrefixes = “07,03,+17”;
What is efficient way to check if the value stored in $prefix is one of the prefixes stored in $allPrefixes
我有一个存储在变量中的前缀 p>
$前缀 =“07”;
code> pre>
以逗号分隔的另一个变量中存储的前缀列表(该列表由用户使用文本框提供) p>
\ n
$ allPrefixes =“07,03,+ 17”;
code> pre>
检查$ prefix中存储的值是否有效的有效方法是什么? 存储在$ allPrefixes p>
div>中的一个前缀
I'd go for a regex to match:
$regex = "/(^|,)".$prefixe."(,|$)/";
preg_match($regex,$allPrefixes);
- On beginning of string before a comma,
- between commas or
- after comma, at end of string
The above regex will match, for example, 07
but not 007
.
General knowledge, not applicable in this case:
If 007
is not likely to appear, or prefixe
is not likely to be a substring of any other prefixe
, then you can use strpos($allPrefixes, $prefixe) > -1
instead, which is quite more efficient.
However
wrapping the $allPrefixes
string between ,
and using strpos might be both efficient and accurate:
strpos(",".$allPrefixes.",", ",".$prefixe.",")
will match 07 but not 007