php比较字符串并返回常用值
我已尝试查找有关此的其他帖子/信息,但它们似乎都不起作用 - 尽管我确信这是一项简单的任务.
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.
例如,我可能有...
String1 = "Product Name - Blue";
String2 = "Blue Green Pink Black Orange";
我想要一个只包含值 Blue 的字符串.我怎样才能做到这一点?提前致谢!
And I would like to have a string only containing the value Blue. How can I do this? Thanks in advance!
推荐答案
你可以使用explode 和 array_intersect 也许?
You can use explode and array_intersect maybe?
此处演示 &这里
<?php
function common($str1,$str2,$case_sensitive = false)
{
$ary1 = explode(' ',$str1);
$ary2 = explode(' ',$str2);
if ($case_sensitive)
{
$ary1 = array_map('strtolower',$ary1);
$ary2 = array_map('strtolower',$ary2);
}
return implode(' ',array_intersect($ary1,$ary2));
}
echo common('Product Name - Blue','Blue Green Pink Black Orange');
返回蓝色";
编辑如果您愿意,可以将其更新为包含不区分大小写的版本.
EDIT Updated it to include a case-insensitive version if you'd like it.
相关文章