2017-10-17 111 views
1

我需要通過比較兩個字符串來獲取不匹配的字符或單詞(即子字符串)。比較兩個字符串並返回不匹配的子字符串

對於防爆:

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

回答

1

我會接近這個我用正則表達式模式替換{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); 
0
$str1 = 'one {text} three'; 
$str2 = 'one two three'; 

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

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

print_r($result); 

此輸出 陣列([1] => 2)

+0

感謝您的回答!但我覺得這是不對的做法,其他答案給出了一些解決方案。 –

相關問題