本文介绍了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.
例如,我可能有...
For example, I may have...
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!
推荐答案
您可以使用和可能?
&
<?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');
返回Blue;
strong> EDIT 将其更新为包含不区分大小写的版本。
EDIT Updated it to include a case-insensitive version if you'd like it.
这篇关于Php比较字符串和返回公共值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!