比较两个字符串并返回不匹配的子字符串

时间:2017-10-17 03:14:19

标签: php

我需要通过比较两个字符串来获得不匹配的字符或单词(即substring)。

对于Ex:

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

2 个答案:

答案 0 :(得分:2)

我会用正则表达式模式替换{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);

答案 1 :(得分:0)

$str1 = 'one {text} three';
$str2 = 'one two three';

$str11 = explode(' ', $str1);
$str22 = explode(' ' , $str2);

$result=array_diff($str22,$str11);

print_r($result);

此输出 数组([1] =>两个)