Php compare strings and return common values(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.
这篇关于php比较字符串并返回常用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php比较字符串并返回常用值


- 带有通配符的 Laravel 验证器 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Laravel 仓库 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01