沃梦达 / 编程问答 / php问题 / 正文

php比较字符串并返回常用值

Php compare strings and return common values(php比较字符串并返回常用值)

本文介绍了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比较字符串并返回常用值

基础教程推荐