PHP 如何测试数组的值之一是否(部分)存在于字符串中?
一定很简单,但找不到我的答案。
如何测试数组中的某个值是否包含在字符串中?
输出应该是 true 或 false。
$array = Array(
0 => 'word1',
1 => 'word2',
2 => 'New York'
3 => 'New car'
);
$string = "Its a sunny day in New York";
试图澄清。在这种情况下 array[3] 不应该匹配。只有 array[2] 应该是。
Must be simple but cant find my answer.
How to test whether one of the values in the array is contained in the string?
Output should be true or false.
$array = Array(
0 => 'word1',
1 => 'word2',
2 => 'New York'
3 => 'New car'
);
$string = "Its a sunny day in New York";
Trying to clarify. In this case array[3] should not be a match. Only array[2] should be.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
in_array
的功能替换是:The functional replacement for your
in_array
would be:更新:
独立于单词边界的解决方案是在输入字符串和搜索词周围添加空格:
或者通过循环术语:
两者都可以放入函数中以简化使用,例如
有一个看看 DEMO
旧答案:
您可以使用常规表达式:
重要的部分是边界字符
\b
在这里。仅当您搜索的值是字符串中的单词(序列)时,您才会获得匹配项。Update:
A word boundary independent solution would be to add spaces around the input string and the search words:
or by looping over the terms:
Both can be put in a function to simplify the use, e.g.
Have a look at a DEMO
Old answer:
You could use regular expressions:
The important part are the boundary characters
\b
here. You will only get a match if the value you search for is a (sequence of) word(s) in the string.暴力方法是:
A brute force method would be:
您可以使用 in_array 函数来实现:
http://php.net/manual/en/function.in-array.php
You can se the in_array function for that:
http://php.net/manual/en/function.in-array.php
像这样的东西吗?
Something like this?