如何使用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);
?>
答案 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 :(得分: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'";
?>