比较两个字符串并返回不匹配的子字符串
问题描述:
我需要通过比较两个字符串来获取不匹配的字符或单词(即子字符串)。比较两个字符串并返回不匹配的子字符串
对于防爆:
$str1 = 'one {text} three'; // {text} is a keyword to find the position where my substring output is located
$str2 = 'one two three';
//I need to return following output
$output = 'two';
答
我会接近这个我用正则表达式模式替换{text}
占位符。然后在第二个字符串上使用preg_match_all
来查找匹配的段。
$str1 = 'one {text} three {text} five';
$str2 = 'one two three four five';
$pattern = str_replace('{text}', '([\w]+)', $str1);
preg_match_all("/{$pattern}/", $str2, $matches);
var_dump($matches);
答
$str1 = 'one {text} three';
$str2 = 'one two three';
$str11 = explode(' ', $str1);
$str22 = explode(' ' , $str2);
$result=array_diff($str22,$str11);
print_r($result);
此输出 阵列([1] => 2)
感谢您的回答!但我觉得这是不对的做法,其他答案给出了一些解决方案。 –