数组键上的模式匹配
我需要从该数组中获取股票值:
Array (
[stock0] => 1
[stockdate0] =>
[stock1] => 3
[stockdate1] => apple
[stock2] => 2 [
stockdate2] =>
)
我需要在此数组上进行模式匹配,其中数组键 =“stock”+ 1 个通配符。 我尝试过使用数组过滤函数来获取 PHP 手册上的所有其他值,但是 空值似乎将其丢弃。我尝试了很多不同的方法,但发现没有任何效果。
这可以做到吗?
I need to get the stock values out of this array:
Array (
[stock0] => 1
[stockdate0] =>
[stock1] => 3
[stockdate1] => apple
[stock2] => 2 [
stockdate2] =>
)
I need to pattern match on this array, where the array key = "stock" + 1 wildcard character.
I have tried using the array filter function to get every other value on the PHP manual but
the empty values seem to throw it out. I tried alot of different things I found but nothing is working.
Can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我希望我的解释正确,并且您想要“stock”、1 个不是换行符的通配符,然后是字符串结尾。
I'm hoping I interpreted correctly and you wanted 'stock', 1 wildcard character thats not a newline, then end of string.
您应该将它们存储为:
You should store those as:
从 PHP 5.6.0 开始,
flag
选项已添加到array_filter
中。这允许您根据数组键而不是其值进行过滤:Since PHP 5.6.0 the
flag
option has been added toarray_filter
. This allows you to filter based on the array keys rather than its values:array_filter 无权访问密钥,因此不是适合您工作的工具。
我相信您想要做的是这样的:
现在 $stockList 看起来像这样:
您可能需要对它稍微大惊小怪,但我认为这就是您所要求的。
然而,如果您可以选择的话,您确实应该遵循杰夫·奥伯的建议。
array_filter does not have access to the key and therefore is not the right tool for your job.
I belive what you're looking to do is this:
Now $stockList looks like this:
You may need to fuss with it a bit, but I think this is what you are asking for.
HOWEVER, you really should be following Jeff Ober's advice if you have the option to do so.
不确定正则表达式和两次翻转的性能有多好,但可维护性极好(循环中没有错误搜寻)。
Not sure how good the performance is due to the regex and two flips, but excellent maintainability (no bug hunting in loops).
好的工作解决方案:
ChronoFish 绿色!
Ok working solution:
Green for ChronoFish!
要允许超过
9
的数字后缀,您可以使用rtrim()
而不是正则表达式来删除数字后缀,然后再次检查搜索字符串是否有相同的匹配项。代码:(演示)
输出:
To allow numeric suffixes that exceed
9
, you can usertrim()
instead of regex to remove the numeric suffix, then check for an identical match again the search string.Code: (Demo)
Output: