Solved

Print difference between two strings in php

Posted on 2010-11-30
10
916 Views
Last Modified: 2012-05-10
Hi,

I need to compare two strings and print difference, for example:
$str1='some-content-here-example';
$str2='some-content-example';
difference: -here

Thanks for any help.
0
Comment
Question by:Zado
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +2
10 Comments
 
LVL 14

Expert Comment

by:Dushyant Sharma
ID: 34237867
0
 
LVL 8

Author Comment

by:Zado
ID: 34238026
doesn't help much, but thanks.
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 34238125
0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 
LVL 8

Author Comment

by:Zado
ID: 34238267
How to make it work?
I set $old and $new variables and try to get some output with echo htmlDiff(); and echo diff(); but I have only 'Array' displayed.
0
 
LVL 8

Author Comment

by:Zado
ID: 34238284
Ok, got it: echo htmlDiff($old, $new);
Thanks.
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 34238307
A bit rough and ready

<?php

$str1 = 'some-content-here-example';
$str2 = 'some-content-example';
$str1sp = preg_split('//', $str1, -1);
$str2sp = preg_split('//', $str2, -1);

$l1 = count($str1sp);
$l2 = count($str2sp);

$length = $l1;
if ($l2 > $l1) {
    $length = $l2;
}
$result = null;
$x = null;
for ($x = 0; $x < $length; $x++) {
    if ($str1[$x] != $str2[$x]) {
        if (!isset($str1[$x])) {
            $result.= $str2[$x];
        } else {
            $result.= $str1[$x];
        }
    }
}

echo $result;
?>

Open in new window

0
 
LVL 8

Author Comment

by:Zado
ID: 34238444
Thanks Darren, but it displays difference and rest of string after that, doesn't work properly.
@MogalManic, how to diplay the difference only instead mark it as delete <del> in whole string? I keep trying do this but with no proper results. Thanks.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34238836
Hi, Zado.  You may or may not have realized it, but you're into one of the classic problems in computer science.  The definition of "difference" is critical to understanding the issue.  Look at this:

$str1='some-content-here-example';
$str2='some-content-example';

You can say that these strings are different at '-here' or at 'here-'.  But this string has only ONE substring difference, so it may be useful only in one small example, not in the abstract solution that you need for all those strings of dates and parenthetical expressions.  I can show you how to start at either end and compare character-by-character until a difference is isolated, but that might not really be what you want.  If you want to give us some more detail about the problem, and some actual test data, you will get a better answer.

And somewhere along the process you may conclude, as I did when I started reading your questions, that it's going to be better to load this data into a data base and process it from the data base, instead of trying to string-manipulate every question.

Some value in understanding this:
http://us.php.net/manual/en/function.levenshtein.php
http://us.php.net/manual/en/function.similar-text.php


Best regards, ~Ray
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 34238906
The htmlDiff() function splits the function by word (space delimeter).  If you want to compare by character, then change the line from
      $diff = diff(explode(' ', $old), explode(' ', $new));
to
      $diff = diff(str_split($old), str_split($new));

There is a side effect though.  It adds spaces in the implode() method call.  Just replace the " " with "".
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 34238931
Here is a tested code example using the test data provided in the original post.  But I expect this is not really what you need, and that there is some sub-hierarchy to your actual, live data.
<?php // RAY_temp_zado.php
error_reporting(E_ALL);
echo "<pre>";

// TEST DATA FROM THE POST AT EE
$str1='some-content-here-example';
$str2='some-content-example';

// MAKE ARRAY SO WE CAN USE AN ITERATOR
$arr1 = str_split($str1);
$arr2 = str_split($str2);

// SET ERROR REPORTING SO WE CAN USE UNDEFINED VALUES AS NULLS
error_reporting(E_ALL ^ E_NOTICE);

// EAT THE ARRAYS FROM THE FRONT
foreach ($arr1 as $ptr => $ltr)
{
    if ($arr2[$ptr] == $ltr)
    {
        unset($arr1[$ptr]);
        unset($arr2[$ptr]);
        continue;
    }
}

// EAT THE ARRAYS FROM THE REAR
$arr1 = array_reverse($arr1);
$arr2 = array_reverse($arr2);
foreach ($arr1 as $ptr => $ltr)
{
    if ($arr2[$ptr] == $ltr)
    {
        unset($arr1[$ptr]);
        unset($arr2[$ptr]);
        continue;
    }
}

// WHICH ONE IS BIGGER"
$cnt1 = count($arr1);
$cnt2 = count($arr2);

if ($cnt1 > $cnt2)
{
    echo implode(NULL, array_reverse($arr1));
}
else
{
    echo implode(NULL, array_reverse($arr2));
}

Open in new window

0

Featured Post

Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

632 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question