prgrm prgrm - 1 month ago 8
PHP Question

Comparing two strings and extract common text

I need to extract common text from two strings.

Example:

$text1 = "My name is John. I like apples. I drive a car. Nice to meet you";
$text2 = "My name is John. I like pears. I don't drive.";

#TODO function

$text3 = get_common_text($text1,$text2);

echo $text3;
//Result: "My name is John. I like . I drive."

Answer

Try this, I think it is right

$text1 = explode( ' ', "My name is John. I like apples. I drive a car. Nice to meet you" );
$text2 = explode( ' ', "My name is John. I like pears. I don't drive." );
foreach( $text2 as $key )
{
    if( strpos( $key, '.' ) !== false )
    {
        $temp = explode( '.', $key );
        $text2[$key] = $temp[0];
    }
}
$common = array();
foreach( $text1 as $key )
{
    if( strpos( '.', $key ) )
    {
        $temp = explode( $key, '.' );
        echo $temp[0];
    }
    if( in_array( $key, $text2 ) )
    {
        $common[] = $key;
    }
}
$common = implode( ' ', $common );

echo $common;

Output is My name is John. I like I drive