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时,这不会产生所述的期望输出。我喜欢梨。我不开车。