-1

i want to compare the string and show to characters which match in both strings in php i tried everything but failed to do this please give me any idea how to do this in php e.g i have two variables

I have to compare $a and $b and give the output as letters whicj are common in both

$a="hello ";
$b= "hell";

output should be : :: hell as first 4 character matches so it should show hell please help me to do this

i have tried everything almost everything which i know or could i find on web What I tried.. I spit the strings to array... Using nested for loop to find the non matched letters... I wrote code more than 35 lines.. But no result :( Please help me ......

LF00
  • 27,015
  • 29
  • 156
  • 295
  • 2
    Welcome to StackOverflow. You should at least provide a sample of the different approaches you are using. – yivi Dec 25 '16 at 10:34
  • please make your question clear, is word and drow have the same 'w', 'o', 'r', 'd'. – LF00 Dec 25 '16 at 10:37
  • 1
    this is an (exact) copy of this question: http://stackoverflow.com/questions/20921590/match-two-strings-and-compare-each-letter-in-php?rq=1 – Jeff Dec 25 '16 at 10:37
  • It would have helped to see those 35 lines of code. Your question is not too clear. What happens to strings like 'color' and 'colour' should the result just be 'colo' or should it be 'color'? What if the same letters are there but in different order. What is the scenario you are using? Compare correct amswers? Be more specific and you will get a perfect answer. – RST Dec 25 '16 at 10:48

2 Answers2

1

In your case, it would be enough to use array_intersect and str_split functions to get characters common to both input strings(of course, if order of characters doesn't matter):

$a = "hello ";
$b = "hell";
$common = array_intersect(str_split(trim($a)), str_split(trim($b)));

print_r($common);

The output:

Array
(
    [0] => h
    [1] => e
    [2] => l
    [3] => l
)

http://php.net/manual/en/function.array-intersect.php

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

This PHP code is the one you need.

<?php


$a = "hello";
$b = "hell";

$str = "";

for ($i=0; $i < strlen($a); $i++) { 
    for ($j=0; $j < strlen($b); $j++) { 
        if ($a[$i]==$b[$j]) {
            $str.=$a[$i];
            break;
        }
    }
}
echo $str;

?>

PHP Strings can be seen as Char arrays so $a[0] get you the first char of the string.

Zenel Rrushi
  • 2,346
  • 1
  • 18
  • 34
  • Apart from whether or not this code will do the job you make a very often made mistake. Do not use the function to determine stringlength (in any language) in the `for` command. The length is not going to change and yet you are calculating it over and over. Put the value in a variable before the `for` command. – RST Dec 25 '16 at 10:50
  • Yep that's right. It's better calculating the length before. – Zenel Rrushi Dec 25 '16 at 14:27