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

标签 php

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

例如:

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

关于php - 比较两个字符串并返回不匹配的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46781914/

相关文章:

javascript - 如何使用 PHP 分割字符串?

php - 在 div 中加载内容而不刷新主页

php - "Not null violation: 7"在 Doctrine2 上使用 manyToOne 和 oneToMany 关系时

javascript - 如何从javascript数组打印空值?

php - 执行 mysqli_query 时 SQL 语法错误

php - 选择,其中 JSON 数组包含

php - curl 获取不到外部网站

php - 将 XAMPP 部署到 Google App Engine

javascript - 使图像可拖动到 HTML5 Canvas,将图像移出 Canvas

php - 如何生成顺序 GUID?