Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 比较两个字符串并提取公共文本_Php_String - Fatal编程技术网

Php 比较两个字符串并提取公共文本

Php 比较两个字符串并提取公共文本,php,string,Php,String,我需要从两个字符串中提取公共文本 例如: $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 J

我需要从两个字符串中提取公共文本

例如:

$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."

试试这个,我认为它是对的

$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;

输出是
我的名字是约翰。我喜欢我开车

你想只提取句子中常见的顺序字符串吗?如果
$text2=“John是我的名字。我喜欢梨。我不开车。”,尝试一下所需的输出结果?@prgrm I驱动器不是常见文本here@PatrickQ我喜欢梨。我开车,点迷路了。所以这不是一个真正的问题?@prgrm仅供参考,当第二个输入是
John is My name时,这不会产生所述的期望输出。我喜欢梨。我不开车。