PHP 比较字符串并返回公共值
我试图找到与此相关的其他帖子/信息,但它们似乎都不起作用 - 尽管我确信这是一项简单的任务。
我有两个字符串,我想要一些代码行来给出它们的共同点。
例如,我可能有...
String1 = "Product Name - Blue";
String2 = "Blue Green Pink Black Orange";
并且我想要一个仅包含值 Blue 的字符串。我该怎么做?提前致谢!
I have tried to find other posts/information on this and none of them seem to work - although I'm sure this is a simple task.
I have two strings, and I would like to have some lines of code that give me the word that they have in common.
For example, I may have...
String1 = "Product Name - Blue";
String2 = "Blue Green Pink Black Orange";
And I would like to have a string only containing the value Blue. How can I do this? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 explode 和 array_intersect 也许?
此处演示 & 此处
返回“Blue”;
编辑如果您愿意,请更新它以包含不区分大小写的版本。
You can use explode and array_intersect maybe?
Demo here & here
Returns "Blue";
EDIT Updated it to include a case-insensitive version if you'd like it.
解决方案是将字符串拆分为两个单词数组 - 使用
explode()< /code>
,例如:
请注意,
explode()
是一个基本解决方案;您可能想使用更复杂的东西,例如preg_split()
,它允许使用更具体的分隔符。And, then, to use [**`array_intersect()`**][3] on those arrays, to find out which words are present in both :
Which, in this case, would give :
A solution would be to split your strings into two arrays of words -- using
explode()
, for instance :Note that
explode()
is a basic solution ; you might want to use something a bit more complex, likepreg_split()
, which allows for more specific delimiters.And, then, to use [**`array_intersect()`**][3] on those arrays, to find out which words are present in both :
Which, in this case, would give :
您想要对每个列表执行explode() 将它们分成数组,然后使用array_intersect() 查找两个数组中的常见单词。
You want to do an explode() on each list to separate them into arrays, then use array_intersect() to find the common words in both arrays.