如何使用PHP在两个具有相同长度的字符串中查找公共字符匹配?

时间:2016-02-18 05:28:39

标签: php regex

如何使用PHP在两个具有相同长度的字符串中查找公共字符匹配?

例如,

$s1 = "ashyjUTY#rj[jkIIO}[hh{FIL]Ojk89y]";
$s2 = "pshyjUTY#r7[jk8rO}[hh{DrL]OjkB7y]";
cMatch($s1, $s2);

输出:

-shyjUTY#r-[jk--O}[hh{--L]Ojk--y]

cMatch函数将预测常见字符匹配,如上所述。

CODE

<?php 
function cMatch($s1, $s2) 
{ 
 $p = $s1; 
 $r = $s2; 
 $m = str_split($p, 1); 
 $n = str_split($r, 1); 
 $a = count($m); 
 $b = count($n); 
 if ($a == $b) { 
   for ($i = 0; $i < $a; $i++) { 
      if ($m[$i] == $n[$i]) { 
        print $m[$i]; 
      } else {
        print "-"; 
      }
   } 
 } else { 
    print "Length of both strings are different!"; } 
 } 
 $x = "ashyjUTY#rj[jkIIO}[hh{FIL]Ojk89y]"; 
 $y = "pshyjUTY#r7[jk8rO}[hh{DrL]OjkB7y]";
 cMatch($x, $y); 
?>

2 个答案:

答案 0 :(得分:2)

请查看以下解决方案:

<?php
$s1="ashyjUTY#rj[jkIIO}[hh{FIL]Ojk89y]";
$s2="pshyjUTY#r7[jk8rO}[hh{DrL]OjkB7y]";
$already=""; // create an empty string
for($i=0;$i<strlen($s2);$i++) // start loop
{
   if ($s1[$i] == $s2[$i]) // done match of character at exact position in both string
   {
       $already .=$s2[$i]; // if match found then assign the character to the newly created variable
   }else{
       $already .='-'; // if not then add - to the variable
   }
}
echo $already; // print the variable and get the common characters along with - included too.
?>

输出: - https://eval.in/520701

注意: -

  1. 此代码将匹配两个字符串中相同位置的字符。

  2. 我相信你可以很容易地将它改成功能。谢谢。

答案 1 :(得分:1)

试试这个,它可能对你有帮助。

<?php
$s1 = "ashyjUTY#rj[jkIIO}[hh{FIL]Ojk89y]";
$s2 = "pshyjUTY#r7[jk8rO}[hh{DrL]OjkB7y]";
$S1_arr = str_split($s1);
$S2_arr = str_split($s2);

$common = implode(array_unique(array_intersect($S1_arr, $S2_arr)));

echo "'$common'";
?>